0
<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

1

5 Answers 5

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this :-

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

    console.log(ar);
</script>

3 Comments

In this case, this should be an object and not an array.
No this will also work for array ..........you can check jsfiddle.net/7j5om9ee
It will work for an array, but not in every way intended. So for example ar.length will still be 0 after your assignment. Array is just a special case of an object. If you do not use any of the added methods, just use a plain object.
0

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";

Comments

0

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

2 Comments

The second approach should use an object instead of an array.
@ShirAzi then all_line_path[data.line_id] should return array.
0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.