1. 程式人生 > 實用技巧 >陣列中的方法

陣列中的方法

@目錄

1.Array.prototype.splice()

splice()函式可向陣列中新增/刪除/替換元素,返回被刪除的元素此方法會改變原陣列****
用法:array.splice(start,amount, item1, item2)

  • start:開始位置
  • amout:整數。要被刪除/替換的元素個數,如果為0表示增加元素。
  • item:沒有item則表示刪除元素,有則表示要新增或者替換的元素。
    (1)新增元素
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 0, "drum");
//運算後的 myFish: ["angel", "clown", "drum", "mandarin", "sturgeon"]

(2) 替換元素

var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 1, "drum");
//運算後的 myFish: ["angel", "clown", "drum", "sturgeon"]

(3) 刪除元素

var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 1); //刪除Index為2開始的一個元素
//運算後的 myFish: ["angel", "clown", "sturgeon"]

Array.prototype.filter()

2.filter() 方法返回一個滿足回撥函式的所有元素組成的陣列此方法不會改變原陣列
callback 被呼叫時傳入三個引數:

  • 元素的值
  • 元素的索引
  • 被遍歷的陣列本身
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word,index) => word.length>6 && index > 2);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Array.prototype.forEach()

3.forEach(callback(currentValue [, index [, array]])[, thisArg]) 方法對陣列的每個元素執行一次callback的函式。返回值為undefined,不改變原陣列
可依次向 callback 函式傳入三個引數:

  • 陣列當前項的值
  • 陣列當前項的索引
  • 陣列物件本身
const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

forEach方法會遍歷陣列中的每一個元素,除非丟擲異常才會終止,如果希望跳出迴圈,可使用every()、some()、find()、findIndex()這些方法。

Array.prototype.map()

4.map函式 返回一個由原陣列每個元素執行回撥函式的結果組成的新陣列。不修改原陣列
callback 函式會被自動傳入三個引數:

  • 陣列元素,
  • 元素索引,
  • 原陣列本身。
    通常在使用map時,callback函式只需要接收一個引數,即正在處理的元素,但並不是map只給回撥傳了一個函式。因此
["1", "2", "3"].map(parseInt);
//輸出[1, NaN, NaN]

這裡的parseInt函式接受兩個引數,(1)元素本身(2)回撥函式的基 第三個引數被parseInt忽視了。

// parseInt(string, radix) -> map(parseInt(value, index))
/*  first iteration (index is 0): */ parseInt("1", 0); // 1
/* second iteration (index is 1): */ parseInt("2", 1); // NaN
/*  third iteration (index is 2): */ parseInt("3", 2); // NaN
Array.prototype.some()

5.some() 方法測試陣列中是不是至少有1個元素通過了被提供的函式測試。返回的是一個Boolean型別的值,不會改變原陣列
callback 函式會被自動傳入三個引數:

  • 陣列元素,
  • 元素索引,
  • 原陣列本身。
Array.prototype.every()

6.every() 方法測試一個數組內的所有元素是否都能通過某個指定函式的測試。它返回一個布林值
返回的是一個Boolean型別的值,不會改變原陣列
callback 函式會被自動傳入三個引數:

  • 陣列元素,
  • 元素索引,
  • 原陣列本身。
const array1 = [1, 30, 39, 29, 10, 13];
array1.every(x => x<40);
// expected output: true