下面是一个包含对象的函数,我希望能够使用参数(即索引)来访问对象内的特定主体。
问题是,当我尝试以这种方式访问属性时,我得到了
undefined
当控制台记录它时。我做错了什么?
moveLeftBtn.on('click', function(nr){
var theBody = {
bodies: {
a: 'foo1',
b: 'foo2',
c: 'foo3'
}
};
var newBody = theBody.bodies[1]; // temporarily hardcoded value instead of argument
console.log(newBody); // <-- undefined, why?
return newBody;
});
编辑
如果我控制台日志theBody.bodies
我可以看到它的值( Object {a: Array[5], b: Array[5], c: Array[5]}
),但是当我尝试使用 [1]
访问它的属性时我明白
undefined
(即使属性包含字符串)。
最佳答案
我在您的代码中看到的唯一问题是您没有返回任何内容。改变 。 。 .
var newBody = theBody.bodies[nr];
。 。 。到 。 。 .
return theBody.bodies[nr];
。 。 。你应该可以开始了。
编辑:哦,在定义 theBody
之后,您还缺少 ;
。
关于javascript - 使用索引访问对象属性会给出 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17095566/