[英]Javascript Access Two-Dimensional Array
I have the following array我有以下数组
var array = [["ABC", "123"], ["DEF", "456"];
How can I get "123", if I look for "ABC? I tried如果我寻找“ABC”,我怎样才能得到“123”?我试过了
array["ABC"][1] //Want Output: 123
array["DEF"][1] //Want Output: 456
You can use Array#find
.您可以使用Array#find
。
var array = [["ABC", "123"], ["DEF", "456"]]; let abc = array.find(x=>x[0]==="ABC"); console.log(abc?.[1]); let def = array.find(x=>x[0]==="DEF"); console.log(def?.[1]); let nothing = array.find(x=>x[0]==="NOTHING"); console.log(nothing?.[1]);
However, using an object or Map
is much better suited to this purpose.但是,使用 object 或Map
更适合此目的。 You can convert your array to an object using Object.fromEntries
.您可以使用 Object.fromEntries 将阵列转换为Object.fromEntries
。
var array = [["ABC", "123"], ["DEF", "456"]]; const obj = Object.fromEntries(array); console.log(obj.ABC); console.log(obj['DEF']);
You can pass the array to the Map
constructor as well.您也可以将数组传递给Map
构造函数。 Map
s are better if you always want to retain insertion order.如果您总是想保留插入顺序, Map
会更好。
var array = [["ABC", "123"], ["DEF", "456"]]; const map = new Map(array); console.log(map.get("ABC")); console.log(map.get("DEF"));
You can use find
to locate the item with the value at index 0
.您可以使用find
来定位索引0
的项目。 If you found, return the value at index 1
.如果找到,则返回索引1
处的值。
const findByFirstValue = (arr, val) => ((res) => res? res[1]: null)(arr.find(v => v[0] === val)) console.log(findByFirstValue([["ABC", "123"], ["DEF", "456"]], 'ABC'))
.as-console-wrapper { top: 0; max-height: 100%;important; }
You can use map
您可以使用map
const array = [["ABC", "123"], ["DEF", "456"]]; const newMap = new Map(); array.map(item=>{ newMap[item[0]] = item; }) console.log(newMap['ABC'][1]);
what you are trying to do is impossible using array, you are not allowed to use:你试图做的事情是不可能使用数组的,你不能使用:
array["ABC"]
since array's indexing is number based, you need to use objects in order to get what you want:由于数组的索引是基于数字的,因此您需要使用对象才能获得所需的内容:
var array = {"ABC": ["123", "789"], "DEF": ["456", "323"]};
now you are able to select them as you want:现在您可以根据需要对它们进行 select :
array['ABC'][1] // 123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.