今天看了一下 有好几种方法 总结一下
1:array.indexOf 此方法判断数组中是否存在某个值,如果存在返回数组元素的下标,否则返回-1
1 2 3 |
let arr = ['something', 'anything', 'nothing', 'anything']; let index = arr.indexOf('nothing'); console.log(index) //结果是2 |
1 2 3 4 5 6 7 8 9 10 11 12 |
function test(fruit) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); }else{ console.log('blue'); } } test('aple')//结果是red |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// ---------- 元素是普通字面值 ---------- 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" } |
from:https://www.cnblogs.com/hepengqiang/p/9822118.html