与多维数组比较给定值

3

我很需要你的帮助。

我想要构建以下结构的数组:

var provinces = [
    ['Ontario','ON'],
    ['Quebec','QC'],
    ['British Columbia','BC'],
    ['Saskatchewan','SK']
];

那么,我想比较值(x)与我的数组,即:
var x = 'Ontario'

if (x matches the value in the array list 'provinces') { then let x = ON }

你如何用JavaScript编写这样的内容?

非常感谢并感激您的所有帮助,

1个回答

0
使用.filter()函数,该函数接收一个真/假返回条件来从数组中检索项目:

var provinces = [
    ['Ontario','ON'],
    ['Quebec','QC'],
    ['British Columbia','BC'],
    ['Saskatchewan','SK']
];

var x = "Ontario";

//Find if any array item matches the word
var result = provinces.filter(function(item) {
  return item[0] == x;
});

//If there's a match, get the second index from the first result from the filter
if(result.length > 0)
  x = result[0][1];

alert(x);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接