JavaScript - 无法设置未定义的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7479520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - cannot set property of undefined
提问by StackOverflowNewbie
My code:
我的代码:
var a = "1",
b = "hello",
c = { "100" : "some important data" },
d = {};
d[a]["greeting"] = b;
d[a]["data"] = c;
console.debug (d);
I get the following error:
我收到以下错误:
Uncaught TypeError: Cannot set property 'greeting' of undefined.
未捕获的类型错误:无法设置未定义的属性“问候语”。
I'm trying to do something similar to an associative array. Why isn't this working?
我正在尝试做一些类似于关联数组的事情。为什么这不起作用?
回答by zzzzBov
you never set d[a]to any value.
您从未设置d[a]为任何值。
Because of this, d[a]evaluates to undefined, and you can't set properties on undefined.
因此,d[a]计算结果为undefined,并且您不能在 上设置属性undefined。
If you add d[a] = {}right after d = {}things should work as expected.
如果您d[a] = {}在d = {}事情应该按预期工作之后立即添加。
Alternatively, you could use an object initializer:
或者,您可以使用对象初始值设定项:
d[a] = {
greetings: b,
data: c
};
Or you could set all the properties of din an anonymous function instance:
或者您可以设置d匿名函数实例中的所有属性:
d = new function () {
this[a] = {
greetings: b,
data: c
};
};
If you're in an environment that supports ES2015 features, you can use computed property names:
如果您处于支持 ES2015 功能的环境中,则可以使用计算属性名称:
d = {
[a]: {
greetings: b,
data: c
}
};
回答by vol7ron
You have to set d[a]to either an associative array, or an object:
您必须设置d[a]为关联数组或对象:
d[a] = [];d[a] = {};
d[a] = [];d[a] = {};
Without setting, this is what's happening:
没有设置,这就是正在发生的事情:
d[a] == undefined, so you're doing undefined['greeting']=b;and by definition, undefined has no properties. Thus, the error you received.
d[a] == undefined,所以你正在做undefined['greeting']=b;,根据定义, undefined 没有属性。因此,您收到了错误。
回答by Polaris878
The object stored at d[a]has not been set to anything. Thus, d[a]evaluates to undefined. You can't assign a property to undefined:). You need to assign an object or array to d[a]:
存储在的对象d[a]尚未设置为任何内容。因此,d[a]评估为undefined。您不能将属性分配给undefined:)。您需要将一个对象或数组分配给d[a]:
d[a] = [];
d[a]["greeting"] = b;
console.debug(d);
回答by wukong
In javascript almost everything is an object, nulland undefinedare exception.
在 javascript 中,几乎所有东西都是对象,null并且undefined是例外。
Instances of Arrayis an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOTan object
实例Array是一个对象。所以你可以设置数组的属性,出于同样的原因,你不能设置未定义的属性,因为它不是一个对象
回答by iohzrd
i'd just do a simple check to see if d[a] exists and if not initialize it...
我只是做一个简单的检查,看看 d[a] 是否存在,如果没有初始化它......
var a = "1",
b = "hello",
c = { "100" : "some important data" },
d = {};
if (d[a] === undefined) {
d[a] = {}
};
d[a]["greeting"] = b;
d[a]["data"] = c;
console.debug (d);

