简体   繁体   中英

Array: Uncaught TypeError: Cannot read property 'push' of undefined

I am writing this program and have checked other similar posts too. But I have difficulty understanding how can I solve this?

Here is html

<body>
<h1>Hello!</h1> Please input start and end of your numbers
<input type="text" id="start" value="1" />
<input type="text" id="end" value="10" />
<button id="btn" onclick="MyFunc(document.getElementById('start').value, document.getElementById('end').value)">Click Me</button>

and here is JS script:

function MyFunc(start, end) {
    for(i=start;i<end;i++)
    {
        var arr = [];
        arr[i].push;
        document.getElementById("demo").innerHTML = arr[i]);
    }
}

I want to construct an array sequence from the first and last values input by user, and then show the array/perform some calculations. I have reviewed other answers at Stack, but couldn't sort out whats wrong with this.

Thank you.

You are declaring an empty array var arr = [] . Right after that you are accessing its contents so for sure it doesn't have any contents so arr[i] is undefined .

I think what you are trying to do is

function MyFunc(start, end) {
    document.getElementById("demo").innerHTML = "";
    var str = "";
    for(i = start; i <= end; i++) {
        str += i;
    }

    document.getElementById("demo").innerHTML = str;
}

JSFiddle Demo

Change

var arr= [];

To

var arr= new Array(size); // size needs to be an integer value.

Also declare the array before the for loop

You always have to initialize an array before adding/removing elements from the same. Since the arr array was not defined, you got a TypeError

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM