avatar
fireworks99
keep hungry keep foolish

arr.some

Description

场景:现在有个数组,数组中必定有0或1个元素是我要找的,除了用for循环还可以用some方法。

let arr = ["red", 123, true, null, undefined, function(){}, { name: "Joy", age: 24 }, ["orange", "yellow"]];

console.log("-------- for --------");
for(let i = 0; i < arr.length; ++i) {
  console.log(arr[i]);
  if(typeof arr[i] === "function") {
    console.log(i);
    break;
  }
}

console.log("-------- forEach --------");
arr.forEach((item, index) => {
  console.log(item);
  if(typeof item === "function") {
    console.log(index);
    return;
  }
})

console.log("-------- some --------");
arr.some((item, index) => {
  console.log(item);
  return typeof item === "function" ? console.log(index) || true : false;
})

some方法可以及时break,forEach不行,forEach必定全部遍历执行。

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy