admin管理员组文章数量:1410737
I'm trying to fill up an Array with a number of elements given by the user. I'm doing this with a prompt window. However, the code doesn't execute, and I get an error on line 9, telling me this:
Uncaught TypeError: Cannot read property 'push' of undefined at fillArrayWithNumberOfElements (line 9).
I searched for an answer online, but they are all pointing out that the array is not properly declared, while I'm pretty sure mine is.
Any help is appreciated, thanks in advance!
var emptyArray = [];
function askInput() {
return (prompt("Please enter a number: "));
}
function fillArrayWithANumberOfElements(array, numberOfElements){
for(var i = 0; i < numberOfElements; i++){
array[i].push(askInput());
}
return array;
}
fillArrayWithANumberOfElements(emptyArray, 5);
I'm trying to fill up an Array with a number of elements given by the user. I'm doing this with a prompt window. However, the code doesn't execute, and I get an error on line 9, telling me this:
Uncaught TypeError: Cannot read property 'push' of undefined at fillArrayWithNumberOfElements (line 9).
I searched for an answer online, but they are all pointing out that the array is not properly declared, while I'm pretty sure mine is.
Any help is appreciated, thanks in advance!
var emptyArray = [];
function askInput() {
return (prompt("Please enter a number: "));
}
function fillArrayWithANumberOfElements(array, numberOfElements){
for(var i = 0; i < numberOfElements; i++){
array[i].push(askInput());
}
return array;
}
fillArrayWithANumberOfElements(emptyArray, 5);
Share
Improve this question
asked May 23, 2017 at 21:12
Sjean PaulSjean Paul
231 silver badge4 bronze badges
1
- 2 array[i] is not an array so there is no push method defined. – James Commented May 23, 2017 at 21:14
2 Answers
Reset to default 5In fillArrayWithANumberOfElements
, array
is the array, not array[i]
. So to push, just use
array.push(askInput());
not
// Not this
array[i].push(askInput());
Alternately if you like, use assignment:
array[i] = askInput();
push
is a function attached to the prototype of the array
type. You're accessing a specific element within the array.
本文标签: arraysjavascript cannot read property 39push39 of undefinedStack Overflow
版权声明:本文标题:arrays - javascript: cannot read property 'push' of undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744956356a2634379.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论