日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JS标准内置对象 数组 的 34 个方法

發(fā)布時(shí)間:2023/12/14 javascript 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JS标准内置对象 数组 的 34 个方法 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

先放一個(gè)語雀的鏈接:

https://www.yuque.com/docs/share/13314a2f-05c0-4de6-8d61-8acd9e566ad4?# 《JS內(nèi)置對(duì)象 Array》

1. at()接收一個(gè)整數(shù)值并返回該索引對(duì)應(yīng)的元素

at() 方法接收一個(gè)整數(shù)值并返回該索引對(duì)應(yīng)的元素,允許正數(shù)和負(fù)數(shù)。負(fù)整數(shù)從數(shù)組中的最后一個(gè)元素開始倒數(shù)。

at() 方法是通用的。其僅期望 this 具有 length 屬性和以整數(shù)為鍵的屬性。

const array1 = [5, 12, 8, 130, 44];let index = 2;console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`); // expected output: "Using an index of 2 the item returned is 8"index = -2;console.log(`Using an index of ${index} item returned is ${array1.at(index)}`); // expected output: "Using an index of -2 item returned is 130"
  • 返回?cái)?shù)組的最后一個(gè)值:
  • // 數(shù)組及數(shù)組元素 const cart = ['apple', 'banana', 'pear'];// 一個(gè)函數(shù),用于返回給定數(shù)組的最后一個(gè)元素 function returnLast(arr) {return arr.at(-1); }// 獲取 'cart' 數(shù)組的最后一個(gè)元素 const item1 = returnLast(cart); console.log(item1); // 輸出:'pear'// 在 'cart' 數(shù)組中添加一個(gè)元素 cart.push('orange'); const item2 = returnLast(cart); console.log(item2); // 輸出:'orange'
  • 比較不同的數(shù)組方法
  • 這個(gè)示例比較了選擇 Array 中倒數(shù)第二個(gè)元素的不同方法。凸顯了 at() 方法的簡(jiǎn)潔性和可讀性。

    // 數(shù)組及數(shù)組元素 const colors = ['red', 'green', 'blue'];// 使用長度屬性 const lengthWay = colors[colors.length-2]; console.log(lengthWay); // 輸出:'green'// 使用 slice() 方法。注意會(huì)返回一個(gè)數(shù)組 const sliceWay = colors.slice(-2, -1); console.log(sliceWay[0]); // 輸出:'green'// 使用 at() 方法 const atWay = colors.at(-2); console.log(atWay); // 輸出:'green'
  • 在非數(shù)組對(duì)象上調(diào)用 at( )
  • at() 方法讀取 this 的 length 屬性并計(jì)算需要訪問的索引。
  • const arrayLike = {length: 2,0: "a",1: "b", }; console.log(Array.prototype.at.call(arrayLike, -1)); // "b"

    2. concat()合并兩個(gè)或多個(gè)數(shù)組

    concat() 方法用于合并兩個(gè)或多個(gè)數(shù)組。此方法不會(huì)更改現(xiàn)有數(shù)組,而是返回一個(gè)新數(shù)組。

    舉例: const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2);console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"]語法: concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN)參數(shù) valueN 可選 數(shù)組和/或值,將被合并到一個(gè)新的數(shù)組中。如果省略了所有 valueN 參數(shù), 則 concat 會(huì)返回調(diào)用此方法的現(xiàn)存數(shù)組的一個(gè)淺拷貝。

  • 合并嵌套數(shù)組:
  • const num1 = [[1]]; const num2 = [2, [3]];const numbers = num1.concat(num2);console.log(numbers); // results in [[1], 2, [3]]// 修改 num1 的第一個(gè)元素 num1[0].push(4);console.log(numbers); // results in [[1, 4], 2, [3]]

    3.copyWithin( ) 淺復(fù)制數(shù)組的一部分到同一數(shù)組中的另一個(gè)位置,并返回它

    copyWithin() 方法淺復(fù)制數(shù)組的一部分到同一數(shù)組中的另一個(gè)位置,并返回它,不會(huì)改變?cè)瓟?shù)組的長度。copyWithin 函數(shù)被設(shè)計(jì)為通用式的,其不要求其 this 值必須是一個(gè)數(shù)組對(duì)象。

    const array1 = ['a', 'b', 'c', 'd', 'e'];// copy to index 0 the element at index 3 console.log(array1.copyWithin(0, 3, 4)); // expected output: Array ["d", "b", "c", "d", "e"]// copy to index 1 all elements from index 3 to the end console.log(array1.copyWithin(1, 3)); // expected output: Array ["d", "d", "e", "d", "e"]
  • 語法:
  • copyWithin(target)

    copyWithin(target, start)

    copyWithin(target, start, end)

  • 參數(shù)
  • target

    0 為基底的索引,復(fù)制序列到該位置。如果是負(fù)數(shù),target 將從末尾開始計(jì)算。如果 target 大于等于 arr.length,將不會(huì)發(fā)生拷貝。如果 target 在 start 之后,復(fù)制的序列將被修改以符合 arr.length。

    start

    0 為基底的索引,開始復(fù)制元素的起始位置。如果是負(fù)數(shù),start 將從末尾開始計(jì)算。如果 start 被忽略,copyWithin 將會(huì)從 0 開始復(fù)制。

    end

    0 為基底的索引,開始復(fù)制元素的結(jié)束位置。copyWithin 將會(huì)拷貝到該位置,但不包括 end 這個(gè)位置的元素。如果是負(fù)數(shù), end 將從末尾開始計(jì)算。如果 end 被忽略,copyWithin 方法將會(huì)一直復(fù)制至數(shù)組結(jié)尾(默認(rèn)為 arr.length)

  • 返回值: 改變后的數(shù)組。
  • 示例:
  • [1, 2, 3, 4, 5].copyWithin(-2) // [1, 2, 3, 1, 2] //從-2的位置開始復(fù)制,復(fù)制的對(duì)象為原數(shù)組[1, 2, 3, 4, 5].copyWithin(0, 3) // [4, 5, 3, 4, 5] //從0的位置開始復(fù)制,將下標(biāo)為3的值復(fù)制到下標(biāo)為0的地方[1, 2, 3, 4, 5].copyWithin(0, 3, 4) // [4, 2, 3, 4, 5][1, 2, 3, 4, 5].copyWithin(-2, -3, -1) // [1, 2, 3, 3, 4][].copyWithin.call({length: 5, 3: 1}, 0, 3); // {0: 1, 3: 1, length: 5}// ES2015 Typed Arrays are subclasses of Array var i32a = new Int32Array([1, 2, 3, 4, 5]);i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5]// On platforms that are not yet ES2015 compliant: [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5]

    4. entries( ) 返回一個(gè)新的數(shù)組迭代器對(duì)象

    entries() 方法返回一個(gè)新的數(shù)組迭代器對(duì)象,該對(duì)象包含數(shù)組中每個(gè)索引的鍵/值對(duì)。

    const array1 = ['a', 'b', 'c'];const iterator1 = array1.entries();console.log(iterator1.next().value); // expected output: Array [0, "a"]console.log(iterator1.next().value); // expected output: Array [1, "b"]
  • 迭代索引和元素
  • const a = ["a", "b", "c"];for (const [index, element] of a.entries()) {console.log(index, element); }// 0 'a' // 1 'b' // 2 'c'
  • 使用 for ... of循環(huán)
  • const array = ["a", "b", "c"]; const arrayEntries = array.entries();for (const element of arrayEntries) {console.log(element); }// [0, 'a'] // [1, 'b'] // [2, 'c']
  • 在非數(shù)組對(duì)象上調(diào)用 entries ()
  • entries() 方法讀取 this 的 length 屬性,然后訪問每個(gè)整數(shù)索引。

    const arrayLike = {length: 3,0: "a",1: "b",2: "c", }; for (const entry of Array.prototype.entries.call(arrayLike)) {console.log(entry); } // [ 0, 'a' ] // [ 1, 'b' ] // [ 2, 'c' ]

    5. every () 測(cè)試一個(gè)數(shù)組內(nèi)的所有元素是否都能通過某個(gè)指定函數(shù)的測(cè)試。

    every() 方法測(cè)試一個(gè)數(shù)組內(nèi)的所有元素是否都能通過某個(gè)指定函數(shù)的測(cè)試。它返回一個(gè)布爾值。若收到一個(gè)空數(shù)組,此方法在任何情況下都會(huì)返回 true。

    const isBelowThreshold = (currentValue) => currentValue < 40;const array1 = [1, 30, 39, 29, 10, 13];console.log(array1.every(isBelowThreshold)); // expected output: true
  • 語法
  • // 箭頭函數(shù) every((element) => { /* … */ } ) every((element, index) => { /* … */ } ) every((element, index, array) => { /* … */ } )// 回調(diào)函數(shù) every(callbackFn) every(callbackFn, thisArg)// 內(nèi)聯(lián)回調(diào)函數(shù) every(function(element) { /* … */ }) every(function(element, index) { /* … */ }) every(function(element, index, array){ /* … */ }) every(function(element, index, array) { /* … */ }, thisArg)參數(shù): callback 用來測(cè)試每個(gè)元素的函數(shù),它可以接收三個(gè)參數(shù): element 用于測(cè)試的當(dāng)前值。 index 用于測(cè)試的當(dāng)前值的索引。 array 調(diào)用 every 的當(dāng)前數(shù)組。
  • 示例:檢測(cè)所有數(shù)組元素的大小
  • 下例檢測(cè)數(shù)組中的所有元素是否都大于 10。function isBigEnough(element, index, array) {return element >= 10; } [12, 5, 8, 130, 44].every(isBigEnough); // false [12, 54, 18, 130, 44].every(isBigEnough); // true箭頭函數(shù)為上面的檢測(cè)過程提供了更簡(jiǎn)短的語法。[12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true

    6. fill () 用一個(gè)固定值填充一個(gè)數(shù)組中從起始索引到終止索引內(nèi)的全部元素。

    fill() 方法用一個(gè)固定值填充一個(gè)數(shù)組中從起始索引到終止索引內(nèi)的全部元素。不包括終止索引。fill 方法故意被設(shè)計(jì)成通用方法,該方法不要求 this 是數(shù)組對(duì)象。當(dāng)一個(gè)對(duì)象被傳遞給 fill 方法的時(shí)候,填充數(shù)組的是這個(gè)對(duì)象的引用。

    const array1 = [1, 2, 3, 4];// fill with 0 from position 2 until position 4 console.log(array1.fill(0, 2, 4)); // expected output: [1, 2, 0, 0]// fill with 5 from position 1 console.log(array1.fill(5, 1)); // expected output: [1, 5, 5, 5]console.log(array1.fill(6)); // expected output: [6, 6, 6, 6]語法: fill(value) fill(value, start) fill(value, start, end)參數(shù):value 用來填充數(shù)組元素的值。 start 可選 起始索引,默認(rèn)值為 0。 end 可選 終止索引,默認(rèn)值為 arr.length。返回值: 修改后的數(shù)組。
  • 示例:
  • [1, 2, 3].fill(4); // [4, 4, 4] [1, 2, 3].fill(4, 1); // [1, 4, 4] [1, 2, 3].fill(4, 1, 2); // [1, 4, 3] [1, 2, 3].fill(4, 1, 1); // [1, 2, 3] [1, 2, 3].fill(4, 3, 3); // [1, 2, 3] [1, 2, 3].fill(4, -3, -2); // [4, 2, 3] [1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3] [1, 2, 3].fill(4, 3, 5); // [1, 2, 3] Array(3).fill(4); // [4, 4, 4] [].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}// Objects by reference. const arr = Array(3).fill({}) // [{}, {}, {}]; // 需要注意如果 fill 的參數(shù)為引用類型,會(huì)導(dǎo)致都執(zhí)行同一個(gè)引用類型 // 如 arr[0] === arr[1] 為 true arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

    7. filter () 創(chuàng)建給定數(shù)組一部分的淺拷貝,過濾數(shù)組。

    filter() 方法創(chuàng)建給定數(shù)組一部分的淺拷貝,其包含通過所提供函數(shù)實(shí)現(xiàn)的測(cè)試的所有元素。filter() 不會(huì)改變?cè)瓟?shù)組,而是返回一個(gè)新數(shù)組。

    const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];const result = words.filter(word => word.length > 6);console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
  • 語法:
  • // 箭頭函數(shù) filter((element) => { /* … */ } ) filter((element, index) => { /* … */ } ) filter((element, index, array) => { /* … */ } )// 回調(diào)函數(shù) filter(callbackFn) filter(callbackFn, thisArg)// 內(nèi)聯(lián)回調(diào)函數(shù) filter(function(element) { /* … */ }) filter(function(element, index) { /* … */ }) filter(function(element, index, array){ /* … */ }) filter(function(element, index, array) { /* … */ }, thisArg)參數(shù): callbackFn 用來測(cè)試數(shù)組中每個(gè)元素的函數(shù)。返回 true 表示該元素通過測(cè)試,保留該元素,false 則不保留。它接受以下三個(gè)參數(shù):element 數(shù)組中當(dāng)前正在處理的元素。index 正在處理的元素在數(shù)組中的索引。array 調(diào)用了 filter() 的數(shù)組本身。返回值: 一個(gè)新的、由通過測(cè)試的元素組成的數(shù)組, 如果沒有任何數(shù)組元素通過測(cè)試,則返回空數(shù)組。

    示例

  • 篩選排除所有較小的值
  • 使用 filter() 創(chuàng)建了一個(gè)新數(shù)組,該數(shù)組的元素由原數(shù)組中值大于 10 的元素組成。

    function isBigEnough(value) {return value >= 10; }const filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]
  • 找出數(shù)組中所有的素?cái)?shù)
  • const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];function isPrime(num) {for (let i = 2; num > i; i++) {if (num % i === 0) {return false;}}return num > 1; }console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
  • 過濾 JSON 中的無效條目
  • 使用 filter() 創(chuàng)建具有非零 id 的元素的 json。
  • const arr = [{ id: 15 },{ id: -1 },{ id: 0 },{ id: 3 },{ id: 12.2 },{},{ id: null },{ id: NaN },{ id: 'undefined' }, ];let invalidEntries = 0;function filterByID(item) {if (Number.isFinite(item.id) && item.id !== 0) {return true;}invalidEntries++;return false; }const arrByID = arr.filter(filterByID);console.log('Filtered Array\n', arrByID); // 過濾后的數(shù)組 // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]console.log('Number of Invalid Entries = ', invalidEntries); // Number of Invalid Entries = 5
  • 在數(shù)組中搜索
  • 使用 filter() 根據(jù)搜索條件來過濾數(shù)組內(nèi)容。
  • const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];/*** 根據(jù)搜索條件(查詢)篩選數(shù)組項(xiàng)*/ function filterItems(arr, query) {return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase())); }console.log(filterItems(fruits, 'ap')); // ['apple', 'grapes'] console.log(filterItems(fruits, 'an')); // ['banana', 'mango', 'orange']

    8. find () 返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的值。

    find() 方法返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的值。否則返回 undefined。find 方法不會(huì)改變數(shù)組。

    const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found); // expected output: 12
    • 如果需要在數(shù)組中找到對(duì)應(yīng)元素的索引,請(qǐng)使用 findIndex()。
    • 如果需要查找某個(gè)值的索引,請(qǐng)使用 Array.prototype.indexOf()。(它類似于 Array.prototype.indexOf(),但只是檢查每個(gè)元素是否與值相等,而不是使用測(cè)試函數(shù)。)
    • 如果需要查找數(shù)組中是否存在值,請(qǐng)使用 Array.prototype.includes()。同樣,它檢查每個(gè)元素是否與值相等,而不是使用測(cè)試函數(shù)。
    • 如果需要查找是否有元素滿足所提供的測(cè)試函數(shù),請(qǐng)使用 Array.prototype.some()。

    語法:

    // 箭頭函數(shù) find((element) => { /* … */ } ) find((element, index) => { /* … */ } ) find((element, index, array) => { /* … */ } )// 回調(diào)函數(shù) find(callbackFn) find(callbackFn, thisArg)// 內(nèi)聯(lián)回調(diào)函數(shù) find(function(element) { /* … */ }) find(function(element, index) { /* … */ }) find(function(element, index, array){ /* … */ }) find(function(element, index, array) { /* … */ }, thisArg)參數(shù): callbackFn 在數(shù)組每一項(xiàng)上執(zhí)行的函數(shù),接收 3 個(gè)參數(shù): element 當(dāng)前遍歷到的元素。 index 當(dāng)前遍歷到的索引。 array 數(shù)組本身。返回值: 數(shù)組中第一個(gè)滿足所提供測(cè)試函數(shù)的元素的值,否則返回 undefined。

    示例:

  • 用對(duì)象屬性查找數(shù)組里的對(duì)象
  • const inventory = [{name: 'apples', quantity: 2},{name: 'bananas', quantity: 0},{name: 'cherries', quantity: 5} ];function isCherries(fruit) {return fruit.name === 'cherries'; }console.log(inventory.find(isCherries)); // { name: 'cherries', quantity: 5 }
  • 使用箭頭函數(shù)和解構(gòu)賦值
  • const inventory = [{name: 'apples', quantity: 2},{name: 'bananas', quantity: 0},{name: 'cherries', quantity: 5} ];const result = inventory.find(({ name }) => name === 'cherries');console.log(result) // { name: 'cherries', quantity: 5 }//不帶花括號(hào)
  • 尋找數(shù)組中的第一個(gè)質(zhì)數(shù)
  • 如何從數(shù)組中尋找質(zhì)數(shù)(如果找不到質(zhì)數(shù)則返回 undefined)
  • function isPrime(element, index, array) {let start = 2;while (start <= Math.sqrt(element)) {if (element % start++ < 1) {return false;}}return element > 1; }console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found console.log([4, 5, 8, 12].find(isPrime)); // 5

    9. findIndex () 數(shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的索引。

    findIndex()方法返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的索引。若沒有找到對(duì)應(yīng)元素則返回 -1。

    const array1 = [5, 12, 8, 130, 44];const isLargeNumber = (element) => element > 13;console.log(array1.findIndex(isLargeNumber)); // expected output: 3

    10. findLast ()數(shù)組中滿足提供的測(cè)試函數(shù)條件的最后一個(gè)元素的值。

    findLast() 方法返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)條件的最后一個(gè)元素的值。如果沒有找到對(duì)應(yīng)元素,則返回 undefined。

    const array1 = [5, 12, 50, 130, 44];const found = array1.findLast((element) => element > 45);console.log(found); // expected output: 130

    11. findLastIndex () 數(shù)組中滿足提供的測(cè)試函數(shù)的最后一個(gè)元素的索引。

    findLastIndex() 方法返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)條件的最后一個(gè)元素的索引。若沒有找到對(duì)應(yīng)元素,則返回 -1。

    const array1 = [5, 12, 50, 130, 44];const isLargeNumber = (element) => element > 45;console.log(array1.findLastIndex(isLargeNumber)); // expected output: 3 (of element with value: 130)

    12. flat()按照一個(gè)可指定的深度遞歸遍歷數(shù)組,并返回新數(shù)組。

    flat() 方法會(huì)按照一個(gè)可指定的深度遞歸遍歷數(shù)組,并將所有元素與遍歷到的子數(shù)組中的元素合并為一個(gè)新數(shù)組返回。

    const arr1 = [0, 1, 2, [3, 4]];console.log(arr1.flat()); // expected output: [0, 1, 2, 3, 4]const arr2 = [0, 1, 2, [[[3, 4]]]];console.log(arr2.flat(2)); // expected output: [0, 1, 2, [3, 4]]

    語法:

    flat() flat(depth)參數(shù): depth 可選 指定要提取嵌套數(shù)組的結(jié)構(gòu)深度,默認(rèn)值為 1。返回值: 一個(gè)包含將數(shù)組與子數(shù)組中所有元素的新數(shù)組。

    示例:

  • 扁平化嵌套數(shù)組
  • 使用 flat(Infinity),可展開任意深度的嵌套數(shù)組

    var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4]var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]]var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6]//使用 Infinity,可展開任意深度的嵌套數(shù)組 var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 扁平化與數(shù)組空項(xiàng)
  • flat() 方法會(huì)移除數(shù)組中的空項(xiàng):

    var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]

    13. flatMap () 使用映射函數(shù)映射每個(gè)元素,然后將結(jié)果壓縮成一個(gè)新數(shù)組。

    flatMap() 方法首先使用映射函數(shù)映射每個(gè)元素,然后將結(jié)果壓縮成一個(gè)新數(shù)組。它與 map 連著深度值為 1 的 flat 幾乎相同,但 flatMap 通常在合并成一種方法的效率稍微高一些。

    const arr1 = [1, 2, [3], [4, 5], 6, []];const flattened = arr1.flatMap(num => num);console.log(flattened); // expected output: Array [1, 2, 3, 4, 5, 6]

    示例:

  • map( ) 與 flatMap( )
  • var arr1 = [1, 2, 3, 4];arr1.map(x => [x * 2]); // [[2], [4], [6], [8]]arr1.flatMap(x => [x * 2]); // [2, 4, 6, 8]// only one level is flattened arr1.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]]

    14. forEach () 對(duì)數(shù)組的每個(gè)元素執(zhí)行一次給定的函數(shù)。

    forEach() 方法對(duì)數(shù)組的每個(gè)元素執(zhí)行一次給定的函數(shù)。

    const array1 = ['a', 'b', 'c'];array1.forEach(element => console.log(element));// expected output: "a" // expected output: "b" // expected output: "c"


    備注: 除了拋出異常以外,沒有辦法中止或跳出 forEach() 循環(huán)。如果你需要中止或跳出循環(huán),forEach() 方法不是應(yīng)當(dāng)使用的工具。

    若你需要提前終止循環(huán),你可以使用:

    • 一個(gè)簡(jiǎn)單的 for 循環(huán)
    • for...of / for...in 循環(huán)
    • Array.prototype.every()
    • Array.prototype.some()
    • Array.prototype.find()
    • Array.prototype.findIndex()

    這些數(shù)組方法則可以對(duì)數(shù)組元素判斷,以便確定是否需要繼續(xù)遍歷:

    • every()
    • some()
    • find()
    • findIndex()

    譯者注:只要條件允許,也可以使用 filter() 提前過濾出需要遍歷的部分,再用 forEach() 處理。

    示例:

  • 不對(duì)未初始化的值做任何操作(稀疏數(shù)組)
  • const arraySparse = [1, 3, /* empty */, 7]; let numCallbackRuns = 0;arraySparse.forEach((element) => {console.log({ element });numCallbackRuns++; });console.log({ numCallbackRuns });// { element: 1 } // { element: 3 } // { element: 7 } // { numCallbackRuns: 3 }如圖,3 到 7 之間的缺失值沒有調(diào)用回調(diào)函數(shù)。
  • 將 for 循環(huán)轉(zhuǎn)換為 forEach
  • const items = ['item1', 'item2', 'item3']; const copyItems = [];// before for (let i = 0; i < items.length; i++) {copyItems.push(items[i]); }// after items.forEach((item) => {copyItems.push(item); });
  • 扁平化數(shù)組
  • const flatten = (arr) => {const result = [];arr.forEach((item) => {if (Array.isArray(item)) {result.push(...flatten(item));} else {result.push(item);}});return result; }// 使用 const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]; console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

    15. from () 對(duì)一個(gè)類似數(shù)組或可迭代對(duì)象創(chuàng)建一個(gè)新的,淺拷貝的數(shù)組實(shí)例。 把非數(shù)組->數(shù)組。

    console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"]console.log(Array.from([1, 2, 3], x => x + x)); // expected output: Array [2, 4, 6]

    語法:

    // 箭頭函數(shù) Array.from(arrayLike, (element) => { /* … */ } ) Array.from(arrayLike, (element, index) => { /* … */ } )// 映射函數(shù) Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg)// 內(nèi)聯(lián)映射函數(shù) Array.from(arrayLike, function mapFn(element) { /* … */ }) Array.from(arrayLike, function mapFn(element, index) { /* … */ }) Array.from(arrayLike, function mapFn(element) { /* … */ }, thisArg) Array.from(arrayLike, function mapFn(element, index) { /* … */ }, thisArg)參數(shù): arrayLike 想要轉(zhuǎn)換成數(shù)組的偽數(shù)組對(duì)象或可迭代對(duì)象。mapFn 可選 如果指定了該參數(shù),新數(shù)組中的每個(gè)元素會(huì)執(zhí)行該回調(diào)函數(shù)。thisArg 可選 可選參數(shù),執(zhí)行回調(diào)函數(shù) mapFn 時(shí) this 對(duì)象。返回值: 一個(gè)新的數(shù)組實(shí)例。

    示例:

  • 從String生成數(shù)組
  • Array.from('foo'); // [ "f", "o", "o" ]
  • 從Set生成數(shù)組
  • const set = new Set(['foo', 'bar', 'baz', 'foo']); Array.from(set); // [ "foo", "bar", "baz" ]
  • 從Map生成數(shù)組
  • const map = new Map([[1, 2], [2, 4], [4, 8]]); Array.from(map); // [[1, 2], [2, 4], [4, 8]]const mapper = new Map([['1', 'a'], ['2', 'b']]); Array.from(mapper.values()); // ['a', 'b'];Array.from(mapper.keys()); // ['1', '2'];
  • 從類數(shù)組對(duì)象(arguments)生成數(shù)組
  • function f() {return Array.from(arguments); }f(1, 2, 3);// [ 1, 2, 3 ]
  • 數(shù)組合并去重
  • function combine(){let arr = [].concat.apply([], arguments); //沒有去重復(fù)的新數(shù)組return Array.from(new Set(arr)); }var m = [1, 2, 2], n = [2,3,3]; console.log(combine(m,n)); // [1, 2, 3]

    16. includes() 判斷一個(gè)數(shù)組是否包含一個(gè)指定的值。

    includes() 方法用來判斷一個(gè)數(shù)組是否包含一個(gè)指定的值,根據(jù)情況,如果包含則返回 true,否則返回 false。使用 includes() 比較字符串和字符時(shí)是區(qū)分大小寫的。

    const array1 = [1, 2, 3];console.log(array1.includes(2)); // expected output: trueconst pets = ['cat', 'dog', 'bat'];console.log(pets.includes('cat')); // expected output: trueconsole.log(pets.includes('at')); // expected output: false

    語法:

    includes(searchElement) includes(searchElement, fromIndex)參數(shù): searchElement 需要查找的元素值。fromIndex 可選 從fromIndex 索引處開始查找 searchElement。 如果為負(fù)值,則按升序從 array.length + fromIndex 的索引開始搜 (即使從末尾開始往前跳 fromIndex 的絕對(duì)值個(gè)索引,然后往后搜尋)。默認(rèn)為 0。

    示例:

    [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true [1, 2, NaN].includes(NaN); // true
  • 如果 fromIndex 大于等于數(shù)組的長度,則將直接返回 false,且不搜索該數(shù)組。
  • var arr = ['a', 'b', 'c'];arr.includes('c', 3); // false arr.includes('c', 100); // false
  • 計(jì)算出的索引小于 0
  • 如果 fromIndex 為負(fù)值,計(jì)算出的索引將作為開始搜索 searchElement 的位置。如果計(jì)算出的索引小于 0,則整個(gè)數(shù)組都會(huì)被搜索。
  • // array length is 3 // fromIndex is -100 // computed index is 3 + (-100) = -97var arr = ['a', 'b', 'c'];arr.includes('a', -100); // true arr.includes('b', -100); // true arr.includes('c', -100); // true arr.includes('a', -2); // false
  • 作為通用方法的 Includes ( )
  • includes() 方法有意設(shè)計(jì)為通用方法。它不要求this值是數(shù)組對(duì)象,所以它可以被用于其他類型的對(duì)象 (比如類數(shù)組對(duì)象)。下面的例子展示了 在函數(shù)的 arguments 對(duì)象上調(diào)用的 includes() 方法。
  • (function() {console.log([].includes.call(arguments, 'a')); // trueconsole.log([].includes.call(arguments, 'd')); // false })('a','b','c');

    17. indexOf() 返回在數(shù)組中可以找到給定元素的第一個(gè)索引。

    indexOf() 方法返回在數(shù)組中可以找到給定元素的第一個(gè)索引,如果不存在,則返回 -1。

    const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];console.log(beasts.indexOf('bison')); // expected output: 1// start from index 2 console.log(beasts.indexOf('bison', 2)); // expected output: 4console.log(beasts.indexOf('giraffe')); // expected output: -1

    語法:

    indexOf(searchElement) indexOf(searchElement, fromIndex)參數(shù): searchElement 要查找的元素。 fromIndex 可選 開始查找的位置。如果該索引值大于或等于數(shù)組長度,意味著不會(huì)在數(shù)組里查找,返回 -1。如果參數(shù)中提供的索引值是一個(gè)負(fù)值,則將其作為數(shù)組末尾的一個(gè)抵消,即 -1 表示從最后一個(gè)元素開始查找,-2 表示從倒數(shù)第二個(gè)元素開始查找,以此類推。注意:如果參數(shù)中提供的索引值是一個(gè)負(fù)值,并不改變其查找順序,查找順序仍然是從前向后查詢數(shù)組。如果抵消后的索引值仍小于 0,則整個(gè)數(shù)組都將會(huì)被查詢。其默認(rèn)值為 0。返回值: 首個(gè)被找到的元素在數(shù)組中的索引位置; 若沒有找到則返回 -1。

    示例:

  • 找出指定元素出現(xiàn)的所有位置
  • const indices = []; const array = ['a', 'b', 'a', 'c', 'a', 'd']; const element = 'a'; let idx = array.indexOf(element); while (idx !== -1) {indices.push(idx);idx = array.indexOf(element, idx + 1); } console.log(indices); // [0, 2, 4]
  • 判斷一個(gè)元素是否在數(shù)組里,不在則更新數(shù)組
  • function updateVegetablesCollection (veggies, veggie) {if (veggies.indexOf(veggie) === -1) {veggies.push(veggie);console.log(`New veggies collection is: ${veggies}`);} else {console.log(`${veggie} already exists in the veggies collection.`);} }const veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];updateVegetablesCollection(veggies, 'spinach'); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, 'spinach'); // spinach already exists in the veggies collection.

    18. isArray() 用于確定傳遞的值是否是一個(gè) Array。

    Array.isArray() 用于確定傳遞的值是否是一個(gè)數(shù)組。

    Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false

    語法:

    Array.isArray(value)參數(shù): value 需要檢測(cè)的值。返回值: 如果值是 Array,則為 true;否則為 false。

    示例:

    // 下面的函數(shù)調(diào)用都返回 true Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); Array.isArray(new Array('a', 'b', 'c', 'd')) Array.isArray(new Array(3)); // 鮮為人知的事實(shí):其實(shí) Array.prototype 也是一個(gè)數(shù)組。 Array.isArray(Array.prototype);// 下面的函數(shù)調(diào)用都返回 false Array.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)) Array.isArray({ __proto__: Array.prototype });

    19. join() 將一個(gè)數(shù)組的所有元素連接成一個(gè)字符串并返回這個(gè)字符串。

    join() 方法將一個(gè)數(shù)組(或一個(gè)類數(shù)組對(duì)象)的所有元素連接成一個(gè)字符串并返回這個(gè)字符串,用逗號(hào)或指定的分隔符字符串分隔。如果數(shù)組只有一個(gè)元素,那么將返回該元素而不使用分隔符。

    const elements = ['Fire', 'Air', 'Water'];console.log(elements.join()); // expected output: "Fire,Air,Water"console.log(elements.join('')); // expected output: "FireAirWater"console.log(elements.join('-')); // expected output: "Fire-Air-Water"

    語法:

    join() join(separator)參數(shù): separator 可選 指定一個(gè)字符串來分隔數(shù)組的每個(gè)元素。如果需要,將分隔符轉(zhuǎn)換為字符串。如果省略,數(shù)組元素用逗號(hào)(,)分隔。如果 separator 是空字符串(""),則所有元素之間都沒有任何字符。返回值: 一個(gè)所有數(shù)組元素連接的字符串。如果 arr.length 為 0,則返回空字符串。

    示例:

  • 用四種不同的方式連接數(shù)組
  • const a = ['Wind', 'Water', 'Fire']; a.join(); // 'Wind,Water,Fire' a.join(', '); // 'Wind, Water, Fire' a.join(' + '); // 'Wind + Water + Fire' a.join(''); // 'WindWaterFire'
  • 在稀疏數(shù)組上使用 join()
  • join() 將空槽視為 undefined,并產(chǎn)生額外的分隔符:

    console.log([1, , 3].join()); // '1,,3' console.log([1, undefined, 3].join()); // '1,,3'
  • 在非數(shù)組對(duì)象上調(diào)用 join()
  • const arrayLike = {length: 3,0: 2,1: 3,2: 4, }; console.log(Array.prototype.join.call(arrayLike)); // 2,3,4 console.log(Array.prototype.join.call(arrayLike, ".")); // 2.3.4

    20. keys() 返回一個(gè)包含數(shù)組中每個(gè)索引鍵的 Array Iterator 對(duì)象。

    keys() 方法返回一個(gè)包含數(shù)組中每個(gè)索引鍵的 Array Iterator 對(duì)象。

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

    語法:

    語法: keys()返回值: 一個(gè)新的 Array 迭代器對(duì)象。

    示例:

  • 索引迭代器會(huì)包含那些沒有對(duì)應(yīng)元素的索引
  • var arr = ["a", , "c"]; var sparseKeys = Object.keys(arr); var denseKeys = [...arr.keys()]; console.log(sparseKeys); // ['0', '2'] console.log(denseKeys); // [0, 1, 2]

    21. lastIndexOf() 返回指定元素在數(shù)組中的最后一個(gè)的索引。

    lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或變量)在數(shù)組中的最后一個(gè)的索引,如果不存在則返回 -1。從數(shù)組的后面向前查找,從 fromIndex 處開始。

    const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];console.log(animals.lastIndexOf('Dodo')); // expected output: 3console.log(animals.lastIndexOf('Tiger')); // expected output: 1

    示例:

  • 查找所有元素:
  • 使用 lastIndexOf 查找到一個(gè)元素在數(shù)組中所有的索引(下標(biāo)),并使用 push 將所有添加到另一個(gè)數(shù)組中。

    var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.lastIndexOf(element);while (idx != -1) {indices.push(idx);idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); }console.log(indices); // [4, 2, 0];

    22. map() 遍歷之后創(chuàng)建新數(shù)組。

    map() 方法創(chuàng)建一個(gè)新數(shù)組,這個(gè)新數(shù)組由原數(shù)組中的每個(gè)元素都調(diào)用一次提供的函數(shù)后的返回值組成。因?yàn)?map 生成一個(gè)新數(shù)組,當(dāng)你不打算使用返回的新數(shù)組卻使用 map 是違背設(shè)計(jì)初衷的,請(qǐng)用 forEach 或者 for-of 替代。

    如果有以下情形,則不該使用 map:

    • 你不打算使用返回的新數(shù)組;或
    • 你沒有從回調(diào)函數(shù)中返回值。
    const array1 = [1, 4, 9, 16];// pass a function to map const map1 = array1.map(x => x * 2);console.log(map1); // expected output: Array [2, 8, 18, 32]

    示例:

  • 求數(shù)組中每個(gè)元素的平方根。
  • const numbers = [1, 4, 9]; const roots = numbers.map((item) => Math.sqrt(item));// roots 現(xiàn)在是 [1, 2, 3] // numbers 依舊是 [1, 4, 9]
  • 使用 map 重新格式化數(shù)組中的對(duì)象。
  • const kvArray = [{ key: 1, value: 10 },{ key: 2, value: 20 },{ key: 3, value: 30 }, ];const reformattedArray = kvArray.map(({ key, value}) => ({ [key]: value }));// reformattedArray 現(xiàn)在是 [{1: 10}, {2: 20}, {3: 30}],// kvArray 依然是: // [{key: 1, value: 10}, // {key: 2, value: 20}, // {key: 3, value: 30}]

    23. pop() 從數(shù)組中刪除最后一個(gè)元素,并返回該元素的值。

    pop() 方法從數(shù)組中刪除最后一個(gè)元素,并返回該元素的值。此方法會(huì)更改數(shù)組的長度。

    const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];console.log(plants.pop()); // expected output: "tomato"console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]plants.pop();console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage"]

    語法:

    pop()返回值: 從數(shù)組中刪除的元素(當(dāng)數(shù)組為空時(shí)返回undefined)。

    24. push() 將一個(gè)或多個(gè)元素添加到數(shù)組的末尾,并返回該數(shù)組的新長度。

    push() 方法將一個(gè)或多個(gè)元素添加到數(shù)組的末尾,并返回該數(shù)組的新長度。

    const animals = ['pigs', 'goats', 'sheep'];const count = animals.push('cows'); console.log(count); // expected output: 4 console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"]animals.push('chickens', 'cats', 'dogs'); console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

    語法:

    push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN)參數(shù): elementN 被添加到數(shù)組末尾的元素。返回值: 當(dāng)調(diào)用該方法時(shí),新的 length 屬性值將被返回。


    示例:

  • 添加元素到數(shù)組:
  • 下面的代碼創(chuàng)建了 sports 數(shù)組,包含兩個(gè)元素,然后又把兩個(gè)元素添加給它。total 變量為數(shù)組的新長度值。

    var sports = ["soccer", "baseball"]; var total = sports.push("football", "swimming");console.log(sports); // ["soccer", "baseball", "football", "swimming"]console.log(total); // 4
  • 合并兩個(gè)數(shù)組
  • var vegetables = ['parsnip', 'potato']; var moreVegs = ['celery', 'beetroot'];// 將第二個(gè)數(shù)組融合進(jìn)第一個(gè)數(shù)組 // 相當(dāng)于 vegetables.push('celery', 'beetroot'); Array.prototype.push.apply(vegetables, moreVegs);console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

    25. reduce() 迭代計(jì)算數(shù)組所有元素的總和。

    reduce() 方法對(duì)數(shù)組中的每個(gè)元素按序執(zhí)行一個(gè)由您提供的 reducer 函數(shù),每一次運(yùn)行 reducer 會(huì)將先前元素的計(jì)算結(jié)果作為參數(shù)傳入,最后將其結(jié)果匯總為單個(gè)返回值。

    第一次執(zhí)行回調(diào)函數(shù)時(shí),不存在“上一次的計(jì)算結(jié)果”。如果需要回調(diào)函數(shù)從數(shù)組索引為 0 的元素開始執(zhí)行,則需要傳遞初始值。否則,數(shù)組索引為 0 的元素將被作為初始值 initialValue,迭代器將從第二個(gè)元素開始執(zhí)行(索引為 1 而不是 0)。

    const array1 = [1, 2, 3, 4];// 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce((previousValue, currentValue) => previousValue + currentValue,initialValue );console.log(sumWithInitial); // expected output: 10

    reducer 逐個(gè)遍歷數(shù)組元素,每一步都將當(dāng)前元素的值與上一步的計(jì)算結(jié)果相加(上一步的計(jì)算結(jié)果是當(dāng)前元素之前所有元素的總和)——直到?jīng)]有更多的元素被相加。

    語法:

    // 箭頭函數(shù) reduce((previousValue, currentValue) => { /* … */ } ) reduce((previousValue, currentValue, currentIndex) => { /* … */ } ) reduce((previousValue, currentValue, currentIndex, array) => { /* … */ } )reduce((previousValue, currentValue) => { /* … */ } , initialValue) reduce((previousValue, currentValue, currentIndex) => { /* … */ } , initialValue) reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue)// 回調(diào)函數(shù) reduce(callbackFn) reduce(callbackFn, initialValue)// 內(nèi)聯(lián)回調(diào)函數(shù) reduce(function(previousValue, currentValue) { /* … */ }) reduce(function(previousValue, currentValue, currentIndex) { /* … */ }) reduce(function(previousValue, currentValue, currentIndex, array) { /* … */ })reduce(function(previousValue, currentValue) { /* … */ }, initialValue) reduce(function(previousValue, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function(previousValue, currentValue, currentIndex, array) { /* … */ }, initialValue)

    參數(shù):

    callbackFn

    一個(gè)“reducer”函數(shù),包含四個(gè)參數(shù):

    • previousValue:上一次調(diào)用 callbackFn 時(shí)的返回值。在第一次調(diào)用時(shí),若指定了初始值 initialValue,其值則為 initialValue,否則為數(shù)組索引為 0 的元素 array[0]。
    • currentValue:數(shù)組中正在處理的元素。在第一次調(diào)用時(shí),若指定了初始值 initialValue,其值則為數(shù)組索引為 0 的元素 array[0],否則為 array[1]。
    • currentIndex:數(shù)組中正在處理的元素的索引。若指定了初始值 initialValue,則起始索引號(hào)為 0,否則從索引 1 起始。
    • array:用于遍歷的數(shù)組。

    initialValue 可選

    作為第一次調(diào)用 callback 函數(shù)時(shí)參數(shù) previousValue 的值。若指定了初始值 initialValue,則 currentValue 則將使用數(shù)組第一個(gè)元素;否則 previousValue 將使用數(shù)組第一個(gè)元素,而 currentValue 將使用數(shù)組第二個(gè)元素。

    返回值:

    使用“reducer”回調(diào)函數(shù)遍歷整個(gè)數(shù)組后的結(jié)果。

    示例:
    1. 求數(shù)組所有值的和

    let sum = [0, 1, 2, 3].reduce(function (previousValue, currentValue) {return previousValue + currentValue }, 0) // sum is 6你也可以寫成箭頭函數(shù)的形式: let total = [ 0, 1, 2, 3 ].reduce(( previousValue, currentValue ) => previousValue + currentValue,0 )
  • 將二維數(shù)組轉(zhuǎn)化為一維數(shù)組
  • let flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(previousValue, currentValue) {return previousValue.concat(currentValue)},[] ) // flattened is [0, 1, 2, 3, 4, 5]你也可以寫成箭頭函數(shù)的形式: let flattened = [[0, 1], [2, 3], [4, 5]].reduce(( previousValue, currentValue ) => previousValue.concat(currentValue),[] )
  • 計(jì)算數(shù)組中每個(gè)元素出現(xiàn)的次數(shù)
  • let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']let countedNames = names.reduce(function (allNames, name) {if (name in allNames) {allNames[name]++}else {allNames[name] = 1}return allNames }, {}) // countedNames is: // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

    26. reverse() 將數(shù)組中元素的位置顛倒,并返回該數(shù)組。

    reverse() 方法將數(shù)組中元素的位置顛倒,并返回該數(shù)組。數(shù)組的第一個(gè)元素會(huì)變成最后一個(gè),數(shù)組的最后一個(gè)元素變成第一個(gè)。該方法會(huì)改變?cè)瓟?shù)組。

    const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // expected output: "array1:" Array ["one", "two", "three"]const reversed = array1.reverse(); console.log('reversed:', reversed); // expected output: "reversed:" Array ["three", "two", "one"]// Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // expected output: "array1:" Array ["three", "two", "one"]

    27. shift() 從數(shù)組中刪除第一個(gè)元素,并返回該元素的值。此方法更改數(shù)組的長度。

    shift() 方法從數(shù)組中刪除第一個(gè)元素,并返回該元素的值。此方法更改數(shù)組的長度。

    示例:

  • 移除數(shù)組中的一個(gè)元素
  • 以下代碼顯示了刪除其第一個(gè)元素之前和之后的 myFish 數(shù)組。它還顯示已刪除的元素:

    let myFish = ['angel', 'clown', 'mandarin', 'surgeon'];console.log('調(diào)用 shift 之前:' + myFish); // "調(diào)用 shift 之前:angel,clown,mandarin,surgeon"var shifted = myFish.shift();console.log('調(diào)用 shift 之后:' + myFish); // "調(diào)用 shift 之后:clown,mandarin,surgeon"console.log('被刪除的元素:' + shifted); // "被刪除的元素:angel"

    28. slice() 返回一個(gè)新的數(shù)組對(duì)象,原始數(shù)組不會(huì)被改變。

    slice() 方法返回一個(gè)新的數(shù)組對(duì)象,這一對(duì)象是一個(gè)由 begin 和 end 決定的原數(shù)組的淺拷貝(包括 begin,不包括end)。原始數(shù)組不會(huì)被改變。

    const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"]console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"]console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"]console.log(animals.slice(-2)); // expected output: Array ["duck", "elephant"]console.log(animals.slice(2, -1)); // expected output: Array ["camel", "duck"]console.log(animals.slice()); // expected output: Array ["ant", "bison", "camel", "duck", "elephant"]


    語法:

    slice() slice(start) slice(start, end)begin 可選: 提取起始處的索引(從 0 開始),從該索引開始提取原數(shù)組元素。 如果該參數(shù)為負(fù)數(shù),則表示從原數(shù)組中的倒數(shù)第幾個(gè)元素開始提取, slice(-2) 表示提取原數(shù)組中的倒數(shù)第二個(gè)元素到最后一個(gè)元素(包含最后一個(gè)元素)。 如果省略 begin,則 slice 從索引 0 開始。 如果 begin 超出原數(shù)組的索引范圍,則會(huì)返回空數(shù)組。end 可選: 提取終止處的索引(從 0 開始),在該索引處結(jié)束提取原數(shù)組元素。 slice 會(huì)提取原數(shù)組中索引從 begin 到 end 的所有元素(包含 begin,但不包含 end)。 slice(1,4) 會(huì)提取原數(shù)組中從第二個(gè)元素開始一直到第四個(gè)元素的所有元素 (索引為 1, 2, 3 的元素)。 如果該參數(shù)為負(fù)數(shù),則它表示在原數(shù)組中的倒數(shù)第幾個(gè)元素結(jié)束抽取。 slice(-2,-1) 表示抽取了原數(shù)組中的倒數(shù)第二個(gè)元素到最后一個(gè)元素。 如果 end 被省略,則 slice 會(huì)一直提取到原數(shù)組末尾。 如果 end 大于數(shù)組的長度,slice 也會(huì)一直提取到原數(shù)組末尾。返回值: 一個(gè)含有被提取元素的新數(shù)組。

    29. some() 測(cè)試數(shù)組中是不是至少有 1 個(gè)元素通過了被提供的函數(shù)測(cè)試。

    some() 方法測(cè)試數(shù)組中是不是至少有 1 個(gè)元素通過了被提供的函數(shù)測(cè)試。它返回的是一個(gè) Boolean 類型的值。如果用一個(gè)空數(shù)組進(jìn)行測(cè)試,在任何情況下它返回的都是false。

    const array = [1, 2, 3, 4, 5];// checks whether an element is even const even = (element) => element % 2 === 0;console.log(array.some(even)); // expected output: true

    示例:

  • 判斷數(shù)組元素中是否存在某個(gè)值
  • var fruits = ['apple', 'banana', 'mango', 'guava'];function checkAvailability(arr, val) {return arr.some(function(arrVal) {return val === arrVal;}); }checkAvailability(fruits, 'kela'); // false checkAvailability(fruits, 'banana'); // true使用箭頭函數(shù)判斷數(shù)組元素中是否存在某個(gè)值: var fruits = ['apple', 'banana', 'mango', 'guava'];function checkAvailability(arr, val) {return arr.some(arrVal => val === arrVal); }checkAvailability(fruits, 'kela'); // false checkAvailability(fruits, 'banana'); // true

    30. sort() 排序,并返回?cái)?shù)組。

    sort() 方法用原地算法對(duì)數(shù)組的元素進(jìn)行排序,并返回?cái)?shù)組。默認(rèn)排序順序是在將元素轉(zhuǎn)換為字符串,然后比較它們的 UTF-16 代碼單元值序列時(shí)構(gòu)建的。

    const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"]const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // expected output: Array [1, 100000, 21, 30, 4]

    語法:

    // 無函數(shù) sort()// 箭頭函數(shù) sort((a, b) => { /* … */ } )// 比較函數(shù) sort(compareFn)// 內(nèi)聯(lián)比較函數(shù) sort(function compareFn(a, b) { /* … */ })

    參數(shù):

    compareFn 可選 用來指定按某種順序進(jìn)行排列的函數(shù)。 如果省略,元素按照轉(zhuǎn)換為的字符串的各個(gè)字符的 Unicode 位點(diǎn)進(jìn)行排序。a 第一個(gè)用于比較的元素。b 第二個(gè)用于比較的元素。描述: 如果指明了 compareFn ,那么數(shù)組會(huì)按照調(diào)用該函數(shù)的返回值排序。 即 a 和 b 是兩個(gè)將要被比較的元素:如果 compareFn(a, b) 大于 0,b 會(huì)被排列到 a 之前。 如果 compareFn(a, b) 小于 0,那么 a 會(huì)被排列到 b 之前; 如果 compareFn(a, b) 等于 0,a 和 b 的相對(duì)位置不變。

    要比較數(shù)字而非字符串,比較函數(shù)可以簡(jiǎn)單的用 a 減 b,如下的函數(shù)將會(huì)將數(shù)組升序排列(如果它不包含 Infinity 和 NaN):

    function compareNumbers(a, b) {return a - b; }

    sort 方法可以使用 函數(shù)表達(dá)式 方便地書寫:

    const numbers = [4, 2, 5, 1, 3]; numbers.sort(function (a, b) {return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5]// 或者const numbers2 = [4, 2, 5, 1, 3]; numbers2.sort((a, b) => a - b); console.log(numbers2); // [1, 2, 3, 4, 5]a-b -> 升序 b-a -> 降序

    31. splice() 通過刪除或替換現(xiàn)有元素或者原地添加新的元素來修改數(shù)組。

    splice() 方法通過刪除或替換現(xiàn)有元素或者原地添加新的元素來修改數(shù)組,并以數(shù)組形式返回被修改的內(nèi)容。此方法會(huì)改變?cè)瓟?shù)組。

    語法:

    splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN)


    參數(shù):

  • start
  • 指定修改的開始位置(從 0 計(jì)數(shù))。如果超出了數(shù)組的長度,則從數(shù)組末尾開始添加內(nèi)容;如果是負(fù)值,則表示從數(shù)組末位開始的第幾位(從 -1 計(jì)數(shù),這意味著 -n 是倒數(shù)第 n 個(gè)元素并且等價(jià)于 array.length-n);如果負(fù)數(shù)的絕對(duì)值大于數(shù)組的長度,則表示開始位置為第 0 位。

  • deleteCount 可選
  • 整數(shù),表示要移除的數(shù)組元素的個(gè)數(shù)。如果 deleteCount 大于 start 之后的元素的總數(shù),則從 start 后面的元素都將被刪除(含第 start 位)。如果 deleteCount 被省略了,或者它的值大于等于array.length - start(也就是說,如果它大于或者等于start之后的所有元素的數(shù)量),那么start之后數(shù)組的所有元素都會(huì)被刪除。如果 deleteCount 是 0 或者負(fù)數(shù),則不移除元素。這種情況下,至少應(yīng)添加一個(gè)新元素。

  • item1, item2, ... 可選
  • 要添加進(jìn)數(shù)組的元素,從start 位置開始。如果不指定,則 splice() 將只刪除數(shù)組元素。

    返回值:

    由被刪除的元素組成的一個(gè)數(shù)組。如果只刪除了一個(gè)元素,則返回只包含一個(gè)元素的數(shù)組。如果沒有刪除元素,則返回空數(shù)組。

    示例:

  • 從索引 2 的位置開始刪除 0 個(gè)元素,插入“drum”和 "guitar"
  • var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2, 0, 'drum', 'guitar');// 運(yùn)算后的 myFish: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] // 被刪除的元素:[], 沒有元素被刪除
  • 從索引 2 的位置開始刪除所有元素
  • var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2);// 運(yùn)算后的 myFish: ["angel", "clown"] // 被刪除的元素:["mandarin", "sturgeon"]

    32. toString() 返回一個(gè)字符串,表示指定的數(shù)組及其元素。

    toString() 方法返回一個(gè)字符串,表示指定的數(shù)組及其元素。

    const array1 = [1, 2, 'a', '1a'];console.log(array1.toString()); // expected output: "1,2,a,1a"

    語法:

    toString()返回值: 一個(gè)表示數(shù)組所有元素的字符串。

    33. unshift() 將一個(gè)或多個(gè)元素添加到數(shù)組的開頭,并返回該數(shù)組的新長度

    const array1 = [1, 2, 3];console.log(array1.unshift(4, 5)); // expected output: 5console.log(array1); // expected output: Array [4, 5, 1, 2, 3]

    示例:

    const arr = [1, 2];arr.unshift(0); // 調(diào)用的結(jié)果是 3,這是新的數(shù)組長度 // arr is [0, 1, 2]arr.unshift(-2, -1); // 新的數(shù)組長度為 5 // arr is [-2, -1, 0, 1, 2]arr.unshift([-4, -3]); // 新的數(shù)組長度為 6 // arr is [[-4, -3], -2, -1, 0, 1, 2]arr.unshift([-7, -6], [-5]); // 新的數(shù)組長度為 8 // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]

    34. values() 返回一個(gè)新的對(duì)象,該對(duì)象包含數(shù)組每個(gè)索引的值。

    values() 方法返回一個(gè)新的 Array Iterator 對(duì)象,該對(duì)象包含數(shù)組每個(gè)索引的值。

    const array1 = ['a', 'b', 'c']; const iterator = array1.values();for (const value of iterator) {console.log(value); }// expected output: "a" // expected output: "b" // expected output: "c"

    返回值:

    一個(gè)新的 Array 迭代對(duì)象。

    示例:

  • 使用 for ... of 循環(huán)進(jìn)行迭代
  • const arr = ['a', 'b', 'c', 'd', 'e']; const iterator = arr.values();for (const letter of iterator) {console.log(letter); } //"a" "b" "c" "d" "e"

    總結(jié)

    以上是生活随笔為你收集整理的JS标准内置对象 数组 的 34 个方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。