js 数组的内置方法(持续更新)

来源:互联网 发布:网络作家笔名 编辑:程序博客网 时间:2024/06/05 16:57

 forEach

forEach() 方法能够方便的让你 遍历数组里的每个元素,你可以在回调函数里对每个元素进行操作。forEach()方法没有返回值,你不需要在回调函数里写return,这是无意义的。

声明:array.forEach(callback, thisArg);

参数:

  1. callback(回调参数接收3个参数)
    • item:当前遍历到的元素
    • index:当前遍历到的下标
    • arr:被遍历的数组
  2. thisArg:对象作为该执行回调时使用(可选)

Demo:

var arr = [1, 2, 4, 5, 7, 8, 9, 0, 100];arr.forEach(function (item, index, arr) {    console.log(item, index, arr);    console.log(this.name); // Evgni0n}, {name: 'Evgni0n'});

 map

map() 方法能够遍历整个数组,然后 返回一个新数组,这个新数组里的元素是经过了指定的回调函数处理过的。

声明:array.map(callback, thisArg)

参数:

  1. callback(回调参数接收3个参数)
    • item:当前遍历到的元素
    • index:当前遍历到的下标
    • arr:被遍历的数组
  2. thisArg:对象作为该执行回调时使用(可选)

返回值:

  1. Array:新的数组

Demo:

var arr = [1, 2, 4, 5, 7, 8, 9, 0, 100];var newArr = arr.map(function (item, index, arr) {    console.log(item, index, arr);    return index;});console.log(newArr === arr);    // false

 filter

filter() 方法能够 过滤掉数组中的某些元素,你可以在回调函数里设定条件,不符合条件的元素都会排除在外。

声明:arr.filter(callback, thisArg)

参数:

  1. callback(回调参数接收3个参数)
    • item:当前遍历到的元素
    • index:当前遍历到的下标
    • arr:被遍历的数组
  2. thisArg:对象作为该执行回调时使用(可选)

返回值:

  1. boolean:
    • true:保留该元素
    • false:不保留该元素

Demo:

var arr = [1, 2, 4, 5, 7, 8, 9, 0, 100];var newArr = arr.filter(function (item, index, arr) {    console.log(item, index, arr);    return item % 2 === 0;});console.log(newArr);    // [2, 4, 8, 0, 100]

every

every() 方法的作用是用指定的回调函数去检查数组中的每个元素,如果对于每个元素,这个回调函数都返回true,则every()返回true。否则,every() 返回false。

声明:arr.every(callback, thisArg)

参数:

  1. callback(回调参数接收3个参数)
    • item:当前遍历到的元素
    • index:当前遍历到的下标
    • arr:被遍历的数组
  2. thisArg:对象作为该执行回调时使用(可选)

返回值:

  1. boolean:
    • true:数组中所有元素都符合条件
    • false:有元素不复合条件

Demo:

var arr = [1, 2, 4, 5, 7, 8, 9, 0, 100];var flag = arr.every(function (item, index, arr) {    return typeof item === 'number';});console.log(flag);  // true

indexOf

返回元素所在的下标

声明:arr.indexOf(searchElement, fromIndex)

参数:

  1. searchElement:数组中元素的值
  2. fromIndex:规定在字符串中开始检索的位置,合法取值是 0 到 arr.length - 1。默认值0(可选)

返回值:

  1. number:
    • -1:没有对应元素

Demo:

var arr = [1, 2, 4, 5, 7, 8, 9, 0, 100];// 元素0所在的下标 -> 7console.log(arr.indexOf(0));    // 7

lastIndexOf

返回数组相同的元素最后一次出现的下标

声明:arr.lastIndexOf(searchElement, fromIndex)

参数:

  1. searchElement:数组中元素的值
  2. fromIndex:规定在字符串中开始检索的位置,合法取值是 0 到 arr.length - 1。默认值0(可选)

返回值:

  1. number:
    • -1:没有对应元素

Demo:

var arr = [1, 2, 4, 5, 7, 8, 9, 0, 100, 5];// 元素5最后一次出现在数组的第9位console.log(arr.lastIndexOf(0));    // 9