如何访问 JavaScript 数组中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15995780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a element in JavaScript array?
提问by TKX
I have a JS array:
我有一个 JS 数组:
a = ["a",["b","c"]]
How I can access string "b" in this array? Thank you very much!
如何访问此数组中的字符串“b”?非常感谢你!
回答by loganfsmyth
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]
.
使用整数索引访问数组。由于这是数组内的数组,因此您使用[1]
访问内部数组,然后使用[0]
.
回答by Tuyen Pham
That is a[1][0]
那是 a[1][0]
alert(a[1][0]) // "b"
回答by 4nkitpatel
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
.
这将给出值作为b
。