Array 數組 相關API

JavaScript的 Array 對象是用於構造數組的全局對象,數組是類似於列表的高階對象。

相關API手冊參考: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

 

  • 創建數組:var 數組名 = [1,2,3] 

var fruits = ['Apple', 'Banana', 'pear'];
console.log(fruits);

 

  • JavaScript 數組的索引是從0開始的,第一個元素的索引爲0,最後一個元素的索引等於該數組的長度減1。如果指定的索引是一個無效值,JavaScript 數組並不會報錯,而是會返回 undefined!!

數組名[元素索引] 例:arr[0]

 

 

  • 打印數組長度

var fruits = ['Apple', 'Banana', 'pear'];
console.log(fruits.length);

 

 

  • 數組名[] 通過索引訪問數組元素

var fruits = ['Apple', 'Banana', 'pear'];
console.log(fruits);//打印

// 訪問第一個數組元素
var first = fruits[0];
console.log(first);//打印

// 訪問最後一個數組元素
var last = fruits[fruits.length - 1];
console.log(last);//打印

 

  • forEach() 遍歷數組

var fruits = ['Apple', 'Banana', 'pear'];
fruits.forEach(function (item, index, array) {
    console.log(item, index);
});

 

  • values() 方法返回一個新的 Array Iterator 對象,包含數組每個索引的值

const fruits = ['Apple', 'Banana', 'pear'];
const iterator = fruits.values();

for (const value of iterator) {
  console.log(value);
}

 

  • unshift() 添加元素到數組的頭部

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var newLength = fruits.unshift('Strawberry');
console.log( fruits );

 

  • push() 添加元素到數組的末尾

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var newLength = fruits.push('Orange');
console.log( fruits );

 

  • shift() 刪除數組最前面(頭部)的元素

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var first = fruits.shift();
console.log( fruits );

 

  • pop() 刪除數組末尾的元素

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var last = fruits.pop();
console.log( fruits );

 

  • indexOf() 找出某個元素在數組中的索引

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var pos = fruits.indexOf('Banana');
console.log( pos );

 

  • splice() 通過索引刪除某個或多個元素

1.通過索引刪除某個或多個元素

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var removedItem = fruits.splice(fruits, 1);
console.log( fruits );

2.從一個索引位置刪除多個元素

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var pos = 1, n = 2;
var removedItems = fruits.splice(pos, n);
console.log( fruits );

console.log(removedItems);

 

  • slice() 複製一個數組

var fruits = ['Apple', 'Banana', 'pear'];
console.log( fruits );

var shallowCopy = fruits.slice();
console.log( shallowCopy );

 

  • from() 方法從一個類似數組或可迭代對象創建一個新的,淺拷貝的數組實例。

console.log(Array.from('foo'));

console.log(Array.from([1, 2, 3], x => x + x));

console.log(Array.from([1, 2, 3], x => x * 2 ));

 

  • isArray() 用於確定傳遞的值是否是一個 Array。如果值是 Array,則爲true; 否則爲false

 

  • Array.of() 方法創建一個具有可變數量參數的新數組實例,而不考慮參數的數量或類型。

Array.of() Array 構造函數之間的區別在於處理整數參數:Array.of(7) 創建一個具有單個元素 7 的數組,而 Array(7) 創建一個長度爲7的空數組(注意:這是指一個有7個空位(empty)的數組,而不是由7undefined組成的數組)。

var array1 = Array.of(7);  
console.log(array1);

var array2 = Array.of(1, 2, 3); 
console.log(array2);

var array3 = Array(7); 
console.log(array3);

var array4 = Array(1, 2, 3); 
console.log(array4);

 

  • concat() 方法用於合併兩個或多個數組。此方法不會更改現有數組,而是返回一個新數組。

用法:數組1.concat(數組2)

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);

 

//連接三個數組

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = ['g', 'h', 'i'];
const array4 = array1.concat( array2,array3 );

console.log(array4);

 

  • copyWithin() 方法 淺複製數組的一部分到同一數組中的另一個位置,並返回它。不改變原數組的長度,但會改變原數組。

用法:copyWithin(target, start, end)

target:複製序列到該位置

start:開始位置索引,如下列:第3位爲d,第4位爲e-移動複製到0

end:結束位置索引,可選項,若無則默認爲末尾元素位置

const array1 = ['a', 'b', 'c', 'd', 'e'];

console.log(array1);

console.log(array1.copyWithin(0, 3, 4));

 

const array1 = ['a', 'b', 'c', 'd', 'e'];

console.log(array1);

console.log(array1.copyWithin(1, 3));

 

  • entries() 方法返回一個新的Array Iterator對象,該對象包含數組中每個索引的鍵/值對。若收到一個空數組,此方法在一切情況下都會返回 true

//判斷array1是否有元素小於40

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 42, 29, 10, 13];
console.log(array1);
console.log(array1.every(isBelowThreshold));

const array2 = [1, 30, 32, 29, 10, 13];
console.log(array2);
console.log(array2.every(isBelowThreshold));

 

  • fill() 方法用一個固定值填充一個數組中從起始索引到終止索引內的全部元素。不包括終止索引。

用法:fill(value, start, end)

value 用來填充數組元素的值

start  可選 起始索引,默認值爲0

end   可選 終止索引,默認值爲 this.length

const array1 = [1, 2, 3, 4];

// 用0填充索引第2位到第4位
console.log(array1.fill(0, 2, 4));

// 用5填充索引第1位到末尾
console.log(array1.fill(5, 1));

// 用6填充全部
console.log(array1.fill(6));

 

  • filter() 方法創建一個新數組, 其包含通過所提供函數實現的測試的所有元素。

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);

 

  • find() 方法返回數組中滿足提供的測試函數的第一個元素的值。否則返回 undefined

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

 

  • findIndex()方法返回數組中滿足提供的測試函數的第一個元素的索引。否則返回-1

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;

//大於13的第一個元素爲130,位於數組索引第三位,輸出: 3
console.log(array1.findIndex(isLargeNumber));

 

  • flat() 方法會按照一個可指定的深度遞歸遍歷數組,並將所有元素與遍歷到的子數組中的元素合併爲一個新數組返回。

flat() 方法會移除數組中的空項

//var newArray = arr.flat([depth])--depth 可選 指定要提取嵌套數組的結構深度,默認值爲 1。
var array1= [1, 2, [3, 4]];
array1.flat();
console.log(array1);
console.log(array1.flat());

//展開深度爲2
var array2 = [1, 2, [3, 4, [5, 6]]];
console.log(array2);
console.log(array2.flat(2));

//使用 Infinity,可展開任意深度的嵌套數組
var array3 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
console.log(array3);
console.log(array3.flat(Infinity));

 

  • flatMap() 方法首先使用映射函數映射每個元素,然後將結果壓縮成一個新數組。它與 map 連着深度值爲1 flat 幾乎相同,但 flatMap 通常在合併成一種方法的效率稍微高一些。

 

  • forEach() 方法對數組的每個元素執行一次給定的函數。

const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

 

  • includes() 方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則返回 true,否則返回false

const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
console.log(pets.includes('at'));

 

 

  • indexOf()方法返回在數組中可以找到一個給定元素完全匹配的第一個的索引,如果不存在,則返回-1

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
console.log(beasts.indexOf('giraffe'));

 

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

const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
console.log(animals.lastIndexOf('Dodo'));
console.log(animals.lastIndexOf('Tiger'));

 

  • join() 方法將一個數組(或一個類數組對象)的所有元素連接成一個字符串並返回這個字符串。如果數組只有一個項目,那麼將返回該項目而不使用分隔符。

const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
console.log(elements.join(''));
console.log(elements.join('-'));

 

  • keys() 方法返回一個包含數組中每個索引鍵的Array Iterator對象。

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
  console.log(key);
}

 

  • map() 方法創建一個新數組,其結果是該數組中的每個元素都調用一次提供的函數後的返回值。

const array1 = [1, 4, 9, 16];
console.log(array1);
const array2 = array1.map(x => x * 2);
console.log(array2);

 

  • unshift() 方法將一個或多個元素添加到數組的開頭,並返回該數組的新長度。該方法會修改原有數組。

const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
console.log(array1);

 

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

const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
console.log(firstElement);

 

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

const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
console.log(animals);
animals.push('chickens', 'cats', 'dogs');
console.log(animals);

 

  • pop()方法從數組中刪除最後一個元素,並返回該元素的值。此方法更改數組的長度。

const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
console.log(plants.pop());
console.log(plants);
plants.pop();
console.log(plants);

 

  • apply() 添加第二個數組的所有元素。

var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];
// 將第二個數組融合進第一個數組
// 會改變原數組 相當於 vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);
console.log(vegetables);

 

  • reducer() 方法對數組中的每個元素執行一個由您提供的reducer函數(升序執行),將其結果彙總爲單個返回值。

Accumulator (acc) (累計器)

Current Value (cur) (當前值)

Current Index (idx) (當前索引)

Source Array (src) (源數組)

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
console.log(array1.reduce(reducer));
//  1 + 2 + 3 + 4 輸出: 10
console.log(array1.reduce(reducer, 5));
// 5 + 1 + 2 + 3 + 4 輸出: 15

 

  • reduceRight() 方法接受一個函數作爲累加器(accumulator)和數組的每個值(從右到左)將其減少爲單個值。

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);
console.log(array1);

 

  • reverse() 方法將數組中元素的位置顛倒,並返回該數組。數組的第一個元素會變成最後一個,數組的最後一個元素變成第一個。該方法會改變原數組。

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
const reversed = array1.reverse();
console.log('reversed:', reversed);
console.log('array1:', array1);//原數組已改變

 

  • sort() 方法用原地算法對數組的元素進行排序,並返回數組。

默認排序順序是在將元素轉換爲字符串,然後比較它們的UTF-16代碼單元值序列時構建的。由於它取決於具體實現,因此無法保證排序的時間和空間複雜性。

//轉換字符串後進行比較

//例如單詞,轉換字符串後按開頭第一個字母排序
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);

//例如數字10,轉換字符串後1開頭 則比2要小
const number= ['2', '3', '5', '10'];
number.sort();
console.log(number);

 

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

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
console.log(animals.slice(2, 4));
console.log(animals.slice(1, 5));

 

  • some() 方法測試數組中是不是至少有1個元素通過了被提供的函數測試。它返回的是一個Boolean類型的值。

const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0;
console.log(array.some(even));

 

  • splice() 方法通過刪除或替換現有元素或者原地添加新的元素來修改數組,並以數組形式返回被修改的內容。此方法會改變原數組。

用法:原數組.splice(X,刪除X個元素,插入內容 可選項 也可多項以逗號隔開)

//從第 2 位開始刪除 0 個元素,插入“Strawberry”
var fruits1 = ['Apple', 'Banana', 'pear'];
console.log(fruits1);
fruits1.splice(2, 0, 'Strawberry');
console.log(fruits1);

 

//從第 2 位開始刪除 0 個元素,插入“Strawberry” 和 "Orange"
var fruits2 = ['Apple', 'Banana', 'pear'];
console.log(fruits2);
fruits2.splice(2, 0, 'Strawberry', 'Orange');
console.log(fruits2);

 

 

//從第 3 位開始刪除 1 個元素
var fruits3 = ['Apple', 'Banana', 'pear', 'Strawberry', 'Orange'];
fruits3.splice(3, 1);
console.log(fruits3);

 

*相似用法參見:

push() / pop() - 在數組末尾增/刪元素;

unshift() / shift() - 在數組首部增/刪元素;

concat() - 把一個(或多個)數組和(或)值與原數組拼接,返回拼接後的數組。

 

  • toLocaleString() 返回一個字符串表示數組中的元素

數組中的元素將使用各自的 toLocaleString 方法轉成字符串,這些字符串將使用一個特定語言環境的字符串(例如一個逗號 ",")隔開。

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });
console.log(localeString);

 

  • toString() 返回一個字符串,表示指定的數組及其元素

const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章