我希望检查一个值是否存在于一个数组对象中。例如:
我有这个数组:
[
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'test'}
]
我想检查这里是否存在 id = 2
。
我希望检查一个值是否存在于一个数组对象中。例如:
我有这个数组:
[
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'test'}
]
我想检查这里是否存在 id = 2
。
var a = [
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'test'}
];
var isPresent = a.some(function(el){ return el.id === 2});
console.log(isPresent);
Array.some()
方法(自 JavaScript 1.6 起)已经足够了,正如前面提到的那样。let a = [
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'test'}
];
let isPresent = a.some(function(el){ return el.id === 2});
console.log(isPresent);
Array.find()
方法。该方法自 ES6 已经存在。let hasPresentOn = a.find(
function(el) {
return el.id === 2
}
);
console.log(hasPresentOn);
var x=[
{id: 1, name: 'foo'},
{id: 2, name: 'bar'},
{id: 3, name: 'test'}
]
var target=x.find(temp=>temp.id==2)
if(target)
console.log(target)
else
console.log("doesn't exists")
试试这个:
let idx = array.findIndex(elem => elem.id === 2)
if (idx !== -1){
// Your element exists
}