简体   繁体   English

Javascript 访问二维数组

[英]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

you can use index to get a value from array in您可以使用索引从数组中获取值

//first level
// array[0] =>["ABC", "123"]
// array[1] => ["DEF", "456"]

//second level 
// array[0][0]=> "ABC"
// array[0][1]=>  "123"

also you can use methods like map or foreach您也可以使用map或 foreach 等方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM