js determines whether an array contains a specified value

1. Array.indexOf This method judges whether there is a value in the array, and returns the index of the array element if it exists, otherwise it returns -1

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

2. array.includes(searchElement[, fromIndex]) This method judges whether there is a value in the array, if it exists, it returns true, otherwise it returns false.
function test(fruit) {

const redFruits = [‘apple’, ‘strawberry’, ‘cherry’, ‘cranberries’];

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

test('aple')//The result is red

3. array.find(callback[, thisArg]) returns the value of the first element in the array that satisfies the condition, if not, returns undefined
// ---------- the element is a normal literal value --- -------
let numbers = [12, 5, 8, 130, 44];
let result = numbers.find(item => { return item> 8; }); console.log(result)


Results: 12

// ---------- elements are objects ----------
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) # Result: Object {id: 3, name: “nothing”} 4. array.findIndex(callback[, thisArg]) returns the index (subscript) of the first element in the array that meets the condition, If not found, return -1, similar to the third method



Guess you like

Origin blog.csdn.net/m0_47402657/article/details/107084856