JavaScript Array 属性、方法 (三)

451 阅读5分钟

JavaScript Array 属性、方法 (一)

JavaScript Array 属性、方法 (二)

forEach()

方法用于调用数组的每个元素,并将元素传递给回调函数

forEach() 对于空数组是不会执行回调函数的。

  • 语法
array.forEach(function(currentValue, index, arr), thisValue)
  • 参数
    • function
      • currentValue: 必须。当前元素的值
      • index: 可选。当前元素的索引值
      • arr: 可选。当前元素属于的数组对象
    • thisValue: 可选。 传递给函数的值一般用 "this" 值。如果这个参数为空, "undefined" 会传递给 "this" 值
  • 返回值

undefined

let array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
  console.log(element);
});

// output: "a"
// output: "b"
// output: "c"
let nums = [1, 2, 3, 4];
let count = 0;
nums.forEach((item) => {
  count += item
});
console.log(count)
// output: 10

includes()

方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。

  • 语法
arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
  • 参数
    • searchElement: 必须。需要查找的元素值。
    • fromIndex: 必须。可选。从该索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0。。
  • 返回值

布尔值。如果找到指定值返回 true,否则返回 false。

let arr = ['a', 'b', 'c'];
 
console.log(arr.includes('c', 2));
// output: true
console.log(arr.includes('c', 3));
// output: false
console.log(arr.includes('c', 100));
// output: false

如果 fromIndex为负值,计算出的索引将作为开始搜索searchElement的位置。如果计算出的索引小于 0,则整个数组都会被搜索。

let arr = ['a', 'b', 'c'];

console.log(arr.includes('a', -100));
// output: true
console.log(arr.includes('b', -100));
// output: true
console.log(arr.includes('c', -100));
// output: true

indexOf()

返回数组中某个指定的元素位置。

该方法将从头到尾地检索数组,看它是否含有对应的元素。

开始检索的位置在数组 start 处或数组的开头(没有指定 start 参数时)。

如果找到一个 item,则返回 item 的第一次出现的位置。开始位置的索引为 0。

如果在数组中没找到指定元素则返回 -1。

  • 语法
array.indexOf(item,start)
  • 参数
    • item: 必须。查找的元素。
    • start: 可选的整数参数。规定在数组中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。
  • 返回值

Number: 元素在数组中的位置,如果没有搜索到则返回 -1。

let fruits = ["Banana", "Orange", "Apple", "Mango"];
let a = fruits.indexOf("Apple");
console.log(a);
// output: 2
let b = fruits.indexof("apple");
console.log(b)
// output: -1
let fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
let a = fruits.indexOf("Apple",4);
console.log(a)
// output: 6

lastIndexOf()

方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始

该方法将从头到尾地检索数组,看它是否含有对应的元素。

开始检索的位置在数组 start 处或数组的开头(没有指定 start 参数时)。

如果找到一个 item,则返回 item 的第一次出现的位置。开始位置的索引为 0。

如果在数组中没找到指定元素则返回 -1。

  • 语法
arr.lastIndexOf(searchElement[, fromIndex])
  • 参数
    • searchElement: 必须。查找的元素。
    • fromIndex: 从此位置开始逆向查找。默认为数组的长度减 1(arr.length - 1),即整个数组都被查找。如果该值大于或等于数组的长度,则整个数组会被查找。如果为负值,将其视为从数组末尾向前的偏移。即使该值为负,数组仍然会被从后向前查找。如果该值为负时,其绝对值大于数组长度,则方法返回 -1,即数组不会被查找。
  • 返回值

Number: 数组中该元素最后一次出现的索引,如未找到返回-1

var animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];

console.log(animals.lastIndexOf('Dodo'));
// output: 3

console.log(animals.lastIndexOf('Tiger'));
//output: 1
var array = [2, 5, 9, 2];
var index = array.lastIndexOf(2);
// index = 3
index = array.lastIndexOf(7);
// index = -1
index = array.lastIndexOf(2, 3);
// index = 3
index = array.lastIndexOf(2, 2);
// index = 0
index = array.lastIndexOf(2, -2);
// index = 0
index = array.lastIndexOf(2, -1);
// index = 3

兼容旧环境

if (!Array.prototype.lastIndexOf) {
  Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
    'use strict';

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var n, k,
        t = Object(this),
        len = t.length >>> 0;
    if (len === 0) {
      return -1;
    }

    n = len - 1;
    if (arguments.length > 1) {
      n = Number(arguments[1]);
      if (n != n) {
        n = 0;
      }
      else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
      }
    }

    for (k = n >= 0
          ? Math.min(n, len - 1)
          : len - Math.abs(n); k >= 0; k--) {
      if (k in t && t[k] === searchElement) {
        return k;
      }
    }
    return -1;
  };
}

join()

方法将一个数组(或类数组对象)的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。

  • 语法
arr.join([separator])
  • 参数
    • separator: 指定一个字符串来分隔数组的每个元素。如果需要,将分隔符转换为字符串。如果缺省该值,数组元素用逗号(,)分隔。如果separator是空字符串(""),则所有元素之间都没有任何字符。
  • 返回值

一个所有数组元素连接的字符串。如果 arr.length 为0,则返回空字符串。

let a = ['Wind', 'Rain', 'Fire'];
let myVar1 = a.join();
console.log(myVar1)
// output: "Wind,Rain,Fire"
let myVar2 = a.join(', ');
console.log(myVar2)
// output: "Wind, Rain, Fire"
let myVar3 = a.join(' + ');
console.log(myVar3)
// output: "Wind + Rain + Fire"
let myVar4 = a.join(''); 
console.log(myVar4)
// output: "WindRainFire"

keys()

法返回一个包含数组中每个索引键的Array Iterator对象。

  • 语法
arr.keys()
  • 返回值

一个新的 Array 迭代器对象

let array1 = ['a', 'b', 'c'];
let iterator = array1.keys(); 
for (let key of iterator) {
  console.log(key);
}
// output: 0
// output: 1
// output: 2

索引迭代器会包含那些没有对应元素的索引

let arr = ["a", , "c"];
let sparseKeys = Object.keys(arr);
let denseKeys = [...arr.keys()];
console.log(sparseKeys);
// output[Array]: ['0', '2']
console.log(denseKeys);
// output[Array]: [0, 1, 2]