xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-11-05 17:03  xgqfrms  阅读(359)  评论(1编辑  收藏  举报