访问对象属性索引给未定义 [英] Accessing object properties with index gives undefined

查看:296
本文介绍了访问对象属性索引给未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个包含一个对象的功能,并且我希望能够向对象物的内部访问一个特定的身体与使用的参数,即与索引

Below is an a function that contains of an object, and I want to be able to access a specific body within the object with the use of an argument, that is with an index.

问题是,当我尝试访问属性就这样,我得到

The problem is that when I try to access a property this way I get

未定义

在控制台日志吧。我在做什么错了?

when console logs it. What am I doing wrong?

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 我可以看到它的值(对象{A:数组[5],B:数组[5] C:数组[5]} ),但是当我试图访问它的属性与 [1] 我得到

If I console log theBody.bodies I can see it's value (Object {a: Array[5], b: Array[5], c: Array[5]}), but when I try to access it's properties with [1] I get

未定义

(即使属性包含字符串)。

(even though the properties contains of strings).

推荐答案

theBody.bodies 是与名为三个属性的对象 A b C 。你没有给它命名的任何财产 1 。这就是为什么 theBody.bodies的值[1] 未定义。如果引用 theBody.bodies ['B'] ,你会发现你期望的特性之一,值'foo1'

theBody.bodies is an object with three properties named a, b, and c. You did not give it any property named 1. That's why the value of theBody.bodies[1] is undefined. If you reference theBody.bodies['b'] you will find one of the properties you expect, with a value of 'foo1'.

这听起来像你只需要在JavaScript数组和对象以及它们如何工作阅读起来。不要让基于像关联数组任何假设你可能在其他语言中都有使用。 JavaScript是它自己有自己的处事方式的语言,所以你只需要学习的。

It sounds like you just need to read up on JavaScript arrays and objects and how they work. Don't make any assumptions based on things like "associative arrays" you may have used in other languages. JavaScript is a language of its own with its own ways of doing things, so you just need to learn those.

这篇关于访问对象属性索引给未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆