简体   繁体   中英

JavaScript array[“index”].push() doesn't work

<script type="text/javascript">
var ar = [];
ar["index"].push("data1");
ar["index"].push("data2");
ar["index3"].push("data5");
ar[55].push("data7");

console.log(ar);
</script>

I get: TypeError: ar.index is undefined

with this

ar["index"].push("data1");

javascript tries to push "data1" into an array. The problem is that it expects an array, which ar["index"] is not as it is undefined.

You first need to initialize it

ar["index"] = [];
ar["index"].push("data1");

push() documentation here

just make it like

<script type="text/javascript">
var ar = [];
ar.push("data1");
ar.push("data2");
ar.push("data5");
ar.push("data7");

console.log(ar);
</script>

Here is dev reference api => link

Try this :-

<script type="text/javascript">
    var ar = [];
    ar["index"] = data1;
    ar["index"] = data2;
    .........
    ........

    console.log(ar);
</script>

Array accepts the method push

What you wanna do is direct access, like a dictionary style... in this case, setting will just do the trick.

var ar = [];
ar["index"] = "data1";

If you're trying create an array of arrays you must check that the "inner" array exists. Something along the lines of this:

if(ar['index'] == null) {
    ar['index'] = [];
    ar['index'].push("data1");
} else {
 ar['index'].push("data1");
}

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