TKX
TKX

Reputation: 338

How to access a element in JavaScript array?

I have a JS array:

a = ["a",["b","c"]]

How I can access string "b" in this array? Thank you very much!

Upvotes: 5

Views: 47252

Answers (3)

4nkitpatel
4nkitpatel

Reputation: 178

As there is an alternative way also to access the element in the array which is:

a['1']['0']  //"b"

as array is internally an object so think indexes is a property of that object so

a = ["a",["b","c"]]

can be internally and object keys or property are internally transfer to string so:

a = {
    '0' : "a",
    '1' : ["b", "c"]
}

this also can refactor to:

a = {
    '0' : "a",
    '1' : {
        '0' : "b",
        '1' : "c"
    }
}

so we can access that index as:

a['1']['0']

this will give the value as b.

Upvotes: 2

NoName
NoName

Reputation: 8025

That is a[1][0]

alert(a[1][0]) // "b"

Upvotes: 5

loganfsmyth
loganfsmyth

Reputation: 161467

You index into an array like this:

a[1][0]

Arrays are accessed using their integer indexes. Since this is an array inside an array, you use [1] to access the inner array, then get the first item in that array with [0].

Upvotes: 7

Related Questions