js判斷一個數(shù)組是否包含一個指定的值
1:array.indexOf 此方法判斷數(shù)組中是否存在某個值,如果存在返回數(shù)組元素的下標(biāo),否則返回-1
let arr = ['something', 'anything', 'nothing', 'anything'];
let index = arr.indexOf('nothing');
console.log(index) //結(jié)果是2
- array.includes(searchElement[, fromIndex]) 此方法判斷數(shù)組中是否存在某個值觅赊,如果存在返回 true,否則返回false岛杀。
function test(fruit) {
const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];
if (redFruits.includes(fruit)) {
console.log('red');
}else{
console.log('blue');
}
}
test('aple')//結(jié)果是red
- array.find(callback[, thisArg]) 返回數(shù)組中滿足條件的第一個元素的值搂擦,如果沒有,返回undefined
// ---------- 元素是普通字面值 ----------
let numbers = [12, 5, 8, 130, 44];
let result = numbers.find(item => {
return item > 8;
});
console.log(result)
# 結(jié)果: 12
// ---------- 元素是對象 ----------
let items = [
{id: 1, name: 'something'},
{id: 2, name: 'anything'},
{id: 3, name: 'nothing'},
{id: 4, name: 'anything'}
];
let item = items.find(item => {
return item.id == 3;
});
console.log(item) # 結(jié)果: Object { id: 3, name: "nothing" }
- array.findIndex(callback[, thisArg]) 返回數(shù)組中滿足條件的第一個元素的索引(下標(biāo)), 如果沒有找到杨拐,返回-1 同第3種方法類似