js Array.some & Array.find All In One
js Array.some & Array.find All In One
Array.some
在找到第一个满足 item, 就会结束循环,提高代码效率;
const array = [1, 2, 3, 4, 5];
const result = array.some((item, index) => {
console.log('item, index =', item, index);
return item > 2;
});
console.log('result =', result);
// some 返回值 boolean
/*
"item, index =" 1 0
"item, index =" 2 1
"item, index =" 3 2
"result =" true
*/
Array.find
const array = [1, 2, 3, 4, 5];
const result = array.find((item, index) => {
console.log('item, index =', item, index);
return item > 2;
});
console.log('result =', result);
// find 返回值 first matched item
/*
"item, index =" 1 0
"item, index =" 2 1
"item, index =" 3 2
"result =" 3
*/
Array.filter
const array = [1, 2, 3, 4, 5];
const result = array.filter((item, index) => {
console.log('item, index =', item, index);
return item > 2;
});
console.log('result =', result);
// filter 返回值 new array
/*
"item, index =" 1 0
"item, index =" 2 1
"item, index =" 3 2
"item, index =" 4 3
"item, index =" 5 4
"result =" Array [3, 4, 5]
*/
Array.some vs Array.find
const times = [0, 0, 0, 1, 0, 1];
times.find(item => item === 1);
// 1
times.find(item => item === 2);
// undefined
times.some(item => item === 1);
// true
times.some(item => item === 2);
// false
refs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/15514188.html
未经授权禁止转载,违者必究!