Javascript 无法设置未定义的属性 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44540391/
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 0 of undefined
提问by aashir khan
This code generates error:
此代码生成错误:
Uncaught TypeError: Cannot set property '0' of undefined
未捕获的类型错误:无法设置未定义的属性“0”
While I want to assign random numbers in array, please help.
虽然我想在数组中分配随机数,但请帮忙。
var array;
for (var i = 1; i < 10; i++) {
array[i] = Math.floor(Math.random() * 7);
}
console.log(array);
回答by Isac
You are missing the array initialization:
您缺少数组初始化:
var array = [];
Taking this into your example, you would have:
将此纳入您的示例,您将拥有:
var array = []; //<-- initialization here
for(var i = 1; i<10;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
Also you should starting assigning values from index 0. As you can see in the log all unassigned values get undefined, which applies to your index 0.
此外,您应该开始从 index 分配值0。正如您在日志中看到的,所有未分配的值都得到了undefined,这适用于您的索引0。
So a better solution would be to start at 0, and adjust the end of forto <9, so that it creates the same number of elements:
因此,一个更好的解决办法是在启动0和调整的结束for到<9,所以它创建的相同数量的元素:
var array = [];
for(var i = 0; i<9;i++) {
array[i]= Math.floor(Math.random() * 7);
}
console.log(array);
回答by Suresh Atta
You haven't told that arrayis an array Tell to javascript that treat that as an array,
你还没有告诉那array是一个数组 告诉 javascript 把它当作一个数组,
var array = [];
回答by Suresh Atta
you need to initialize the array first
你需要先初始化数组
var array = [];
after adding this line your code should work properly
添加此行后,您的代码应该可以正常工作

