无法遍历 javascript 中的对象数组

Unable to loop through array of objects in javascript

我想遍历对象数组,但无法找到每个对象的键。我做错了什么?

Javascript/jQuery代码:

var position = [];

$('.box').each(function(){

var id = $(this).attr('id');

var offset = $(this).offset();

var offsetX = offset.left;

var offsetY = offset.top;

position.push('{"id":'+id+',"offX":'+offsetX+',"offY":'+offsetY+'}');

});

for (var i = 0; i < position.length; i++) {
  console.log(position[i].id); // i get the error of undefined
}

Html 标记:

<div id="parent">

    <div class="box" id="1">1</div>
    <div class="box" id="2">2</div>
    <div class="box" id="3">3</div>
    <div class="box" id="4">4</div>
    <div class="box" id="5">5</div>
    <div class="box" id="6">6</div>
    <div class="box" id="7">7</div>
    <div class="box" id="8">8</div>
    <div class="box" id="9">9</div>
    <div class="box" id="10">10</div>

</div> 

这里是jsfiddle

position.push('{"id":'+id+',"offX":'+offsetX+',"offY":'+offsetY+'}');

好吧,那不是一个对象,而是一个 JSON 字符串(如果你够幸运并且它是有效的)。使用正确的对象字面量:

position.push({"id":id, "offX":offsetX, "offY":offsetY});

然后您将能够访问其 .id 属性。

您正在向数组中添加一个字符串。您要添加一个对象。

position.push({id: id,offX: offsetX,offY: offsetY});

我看过你的代码,看来问题出在你的陈述上:

$('.box').each(function(){});

即使语法正确,也可能有其他问题导致这种情况发生。以下是一些可能有误的建议:

  • 缺少您正在引用的 JQuery 文件,或者您根本没有引用文件。

确保您拥有在该网站上找到的家庭 testing/ServerTesting 的 JQuery 文件:Click Here

  • 确保您在脚本中引用了 JQuery 文件:
script src="jquery-1.11.2.min.js"
  • 如果您不是 运行 html 5 那么请务必添加:
script type="javascript/text"