我有此列表:
list1 = [['phone1','123'],['phone2','125'],...]
我想检查变量x是否在列表中
例如,当x =='123'时,它不会被推送到list1
。
我尝试了这段代码,但是没有得到它:
const phone = this.eForm.value['phone'];
const name= this.eForm.value['name'];
for (let i = 0; i < list1.length; i++) {
if (list1[i][1] == phone) {
list1.push([name, phone]);
}
}
答案 0 :(得分:2)
这将搜索您记录的2D数组,并允许您使用find()
进行搜索。选中docs here。
let list1 = [
['phone1', '123'],
['phone2', '125']
];
let phone = '123';
let phoneName = 'phone3';
//Find() method will search each item of the array and return the result
let foundResult = list1.find((listItem) => {
return listItem[1] === phone
});
//Find() method will search each item of the array and return the result. This one will not find a match.
let notFoundResult = list1.find((listItem) => {
return listItem[1] === '555-555-5555'
});
console.log(`First Output: ${(foundResult) ? 'Found Something!' : 'Nope'}`);
console.log(`Second Output: ${ (notFoundResult) ? 'Found Something!' : 'Nope'}`);
答案 1 :(得分:1)
let list1 = [['phone1','123'],['phone2','125']];
const phone = 'phone3';
if(list1.reduce((n, element) => { return n + (element[0] == phone) }, 0) > 0)
{
console.log("phone3 exists in list1");
}
else
{
console.log("phone3 is not anywhere in list1");
}
reduce函数返回的值表示list1数组中出现“ phone3”的次数。
因此,如果大于0,则存在“ phone3”。