js判断一个数组是否包含一个指定的值

63 篇文章 1 订阅
54 篇文章 1 订阅

js判断一个数组是否包含一个指定的值,几种方法 总结一下:
1:array.indexOf 此方法判断数组中是否存在某个值,如果存在返回数组元素的下标,否则返回-1。

let arr = ['something', 'anything', 'nothing', 'anything'];
let index = arr.indexOf('nothing');
console.log(index) //结果是2

2. array.includes(searchElement[, fromIndex]) 此方法判断数组中是否存在某个值,如果存在返回 true,否则返回false。

function test(fruit) {

const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

if (redFruits.includes(fruit)) {
console.log('red');
}else{
console.log('blue');
}
}

test(‘aple’)//结果是red

3. array.find(callback[, thisArg]) 返回数组中满足条件的第一个元素的值,如果没有,返回undefined

// ---------- 元素是普通字面值 ----------
let numbers = [12, 5, 8, 130, 44];
let result = numbers.find(item => {
    return item > 8;
});
console.log(result)
# 结果: 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) # 结果: Object { id: 3, name: “nothing” }
4. array.findIndex(callback[, thisArg]) 返回数组中满足条件的第一个元素的索引(下标), 如果没有找到,返回-1 同第3种方法类似

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值