JavaScript查找数组

2020-01-13  本文已影响0人  段煜华

JavaScript中数组的常用操作之查找数组

Array.includes() 方法

array.includes(itemToSearch [,fromIndex])返回一个布尔值,array 是否包含itemToSearch。可选参数fromIndex,默认为0,表示开始搜索的索引。
如下所示:判断2和99是否存在于一组数字中:

const numbers = [1, 2, 3, 4, 5];
numbers.includes(2);  // => true
numbers.includes(99); // => false

Array.find() 方法

Array.find(callback[, thisArg]) 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
在每个遍历中callback(item[, index[, array]])使用参数调用:(当前项索引数组本身
thisArg可选,执行回调时用作this 的对象。

如下所示,找到数组中的第一个大于10的数:

const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);  //=> 12

Array.findIndex() 方法

Array.find(callback[, thisArg]) 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 -1
在每个遍历中callback(item[, index[, array]])使用参数调用:(当前项索引数组本身
thisArg可选,执行回调时用作this 的对象。
以下示例查找数组中素数的元素的索引(如果不存在素数,则返回-1)。

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
上一篇 下一篇

猜你喜欢

热点阅读