JavaScript - 无法设置undefined的属性 [英] JavaScript - cannot set property of undefined

查看:214
本文介绍了JavaScript - 无法设置undefined的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

    var a = "1",
        b = "hello",
        c = { "100" : "some important data" },
        d = {};

        d[a]["greeting"] = b;
        d[a]["data"] = c;

        console.debug (d);

我收到以下错误:


Uncaught TypeError:无法设置未定义的属性'greeting'。

Uncaught TypeError: Cannot set property 'greeting' of undefined.

我正在尝试做类似的事情到一个关联数组。为什么这不起作用?

I'm trying to do something similar to an associative array. Why isn't this working?

推荐答案

你从未设置 d [a] 到任何值。

因此, d [a] 的计算结果为未定义,并且您无法在 undefined 上设置属性。

Because of this, d[a] evaluates to undefined, and you can't set properties on undefined.

如果添加 d [a] = {} d = {} 之后,事情应按预期工作。

If you add d[a] = {} right after d = {} things should work as expected.

或者,您可以使用对象初始值设定项:

Alternatively, you could use an object initializer:

d[a] = {
    greetings: b,
    data: c
};

或者你可以设置 d 在一个匿名函数实例中:

Or you could set all the properties of d in an anonymous function instance:

d = new function () {
    this[a] = {
        greetings: b,
        data: c
    };
};






如果您所在的环境支持ES2015功能,您可以使用计算属性名称

d = {
  [a]: {
    greetings: b,
    data: c
  }
};

这篇关于JavaScript - 无法设置undefined的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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