javascript 未捕获的类型错误:无法设置未定义的属性“文本”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15863896/
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
Uncaught TypeError: Cannot set property 'text' of undefined
提问by Udai Arora
I am getting an error "Uncaught TypeError: Cannot set property 'text' of undefined" on running the following
我在运行以下命令时收到错误“未捕获的类型错误:无法设置未定义的属性‘文本’”
var years= new Array(113);
for(i=0;i<113;i++){
years[i]["text"]=i+1900;
years[i]["value"]=i+1900;
}
Basically, I want something like this to be generated with a loop
基本上,我想用循环生成这样的东西
var years= [
{ text: "1990", value: 1990, },
{ text: "1991", value: 1991, }, //till 2012
];
Any help?
有什么帮助吗?
回答by T.J. Crowder
You want literal notation:
你想要文字符号:
var years= new Array(113);
for(i=0;i<113;i++){
years[i] = {text: String(i + 1900), value: i + 1900};
}
The reason you were getting the error is that you never assigned anything to years[i]
, but you were trying to useit in the expression years[i]["text"]
(which means "get the property with the name from i
from the years
object, and then get the property "text"
from that).
您收到错误的原因是您从未将任何内容分配给years[i]
,但您试图在表达式中使用它years[i]["text"]
(这意味着“i
从years
对象中获取具有名称的属性,然后从中获取属性"text"
)。
Note that there's no benefit in attempting to pre-allocate room for a standard array in JavaScript, because JavaScript standard arrays aren't really arrays at all. So perhaps:
请注意,尝试为 JavaScript 中的标准数组预先分配空间没有任何好处,因为 JavaScript 标准数组根本不是真正的数组。所以也许:
var years= [];
for(i=0;i<113;i++){
years[i] = {text: String(i + 1900), value: i + 1900};
}
Similarly, you could just loop from 1900
(inclusive) to 2013
(exclusive) rather than doing all of that addition in the loop:
同样,您可以只从1900
(包含)到2013
(不包含)循环,而不是在循环中进行所有添加:
var years= [];
for(i=1900;i<2013;i++){
years.push({text: String(i), value: i});
}
回答by Daishy
years[i] is not set to anything (years[i] == undefined
), so you can't access text on it. Try it with the following:
years[i] 未设置为任何内容 ( years[i] == undefined
),因此您无法访问其上的文本。请尝试以下操作:
var years = new Array(113);
for(i=0; i < 113; i++) {
years[i] = {"text": i+1900, "value": i+1900};
}
or
或者
var years = new Array();
for(i=0; i < 113; i++) {
years.push({"text": i+1900, "value": i+1900});
}
回答by 0x499602D2
Your question has already been answered but I would suggest using the array literal notation instead of the explicit constructor call.
您的问题已得到解答,但我建议使用数组文字表示法而不是显式构造函数调用。
var years = [];
for (var i = 0; i < 133; ++i)
{
years[i] = {
text: (i + 1900).toString(),
value: i + 1900
};
}