将给定值与多维数组进行比较

时间:2015-05-29 20:24:16

标签: javascript arrays string multidimensional-array

我真的需要你的帮助。

我想构建和构建如下所示的数组。:

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

然后,id喜欢将值(x)与我的数组进行比较,即:

var x = 'Ontario'

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

你如何在javascript中写这样的东西?

非常感谢和感谢你的帮助,

1 个答案:

答案 0 :(得分:0)

使用接收true / false返回条件的.filter()函数从数组中检索itens:



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);




相关问题