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
Add a ment  | 

2 Answers 2

Reset to default 5

In 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