我真的需要你的帮助。
我想构建一个像下面这样的数组:
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写这样的东西?
非常感谢你的帮助,
使用.filter()
函数,它接收一个true/false返回条件从数组中检索项:
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);