我真的需要你的帮助。
我想像下面这样构造和构建一个数组:
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 写这样的东西?
非常感谢您的帮助,
最佳答案
使用 .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);
关于javascript - 将给定值与多维数组进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30538444/