【问题标题】:Need sample javascript object literal需要示例 javascript 对象文字
【发布时间】:2011-01-19 01:57:04
【问题描述】:

我需要一个可以通过以下方式访问的示例 js 对象字面量:

hist.undo[0].operation[0].x // would print '2' or whatever
hist.undo[0].operation[0].y // would print '21' or whatever
// [...]
hist.undo[2].operation[0].x // would print '32' or whatever
hist.undo[2].operation[0].y // would print '12' or whatever

谢谢!

【问题讨论】:

标签: javascript json object literals


【解决方案1】:

(working jsfiddle example here)

var sample_operation_member = {"x": 100, "y": 250};
var sample_undo_member = { "operation" : [sample_operation_member, sample_operation_member,sample_operation_member] };

var hist = {
   "undo": [
      sample_undo_member,
      sample_undo_member,
      sample_undo_member,
      sample_undo_member
   ]
}

alert(hist.undo[0].operation[0].x);

或者,更详细地说:

var hist = {
    undo: [
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]},
        {"operation": [{"x": 100, "y":100},{"x": 100, "y":100},{"x": 100, "y":100}]}
    ]
}

alert(hist.undo[0].operation[0].x);

【讨论】:

  • 您可能需要考虑遵循规范。 json.org“字符串是零个或多个 Unicode 字符的序列,用双引号括起来,使用反斜杠转义”虽然大多数解析器在没有引号的情况下工作,但包含它们是个好主意
  • 只是记住ObjectLiteral != SJON应该是一样的,但并不总是一样的
  • 再次感谢。我已经更新了我的答案和 JSFiddle example 以纳入 @Richardakacyberkiwi 的建议
【解决方案2】:
<html>
<head>
</head>
<body>
test
<script>
hist = {
 "undo" : [
  {
   "operation": [ {"x":"2","y":"21"}, {"x":"x2","y":"y21"} ]
  },
  {
   "operation": [ {"x":"99","y":"88"} ]
  },
  {
   "operation": [ {"x":"32","y":"12"} ]
  }
 ]
 };
alert(hist.undo[0].operation[0].x);
alert(hist.undo[0].operation[0].y);
alert(hist.undo[2].operation[0].x);
alert(hist.undo[2].operation[0].y);
</script>
</body>
</html>

【讨论】:

  • 只有在有 1 次撤消时才有效?我需要包含多个操作的多个撤消对象。所以基本上,每个 hist 对象都包含多个 undo 对象。每个撤消对象包含多个操作对象,这些操作对象本身包含多个操作。谢谢
  • 您可能会感到困惑。从索引 undo[2] 来看,应该清楚那里有 3 个 undo 对象。请再看看。符号 ' "undo" : [ ' 表示 "undo" 是一个数组,在该数组中,您会看到 3 个未命名的对象。
  • 啊,我的错。谢谢,这正是我需要的。
【解决方案3】:
hist = { "undo" : [
      {"operation":[
        {"x":2,"y":21},
        {"x":3,"y":31}
      ]},
      {"operation":[
        {"x":4,"y":41},
        {"x":5,"y":51}
      ]},
      {"operation":[
        {"x":6,"y":61},
        {"x":7,"y":71}
      ]}
     ]
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多