組操作是 JavaScript 中非常重要也非常常用的技巧。本文整理了常用的數組操作方法(包括 ES6 的 map、forEach、every、some、filter、find、from、of 等),熟悉了這些數組操作方法,編寫程序也會更加簡潔高效。
push()可以將某些值加入到數組的最后一個位置,不限制添加數量,添加的內容使用逗號隔開即可,加入后數組長度會增加。
使用push()后會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
a.push(9, 10);
console.log(a); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pop()會移除 (取出) 數組的最后一個元素。
使用pop()后會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
let b=a.pop();
console.log(a); // [1, 2, 3, 4, 5, 6, 7]
console.log(b); // 8
shift()會移除 (取出) 數組的第一個元素。
使用shift()后會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
let b=a.shift();
console.log(a); // [2, 3, 4, 5, 6, 7, 8]
console.log(b); // 1
unshift()會將指定的元素添加到第一個位置。
使用nushift()后會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
a.unshift(100,200,300);
console.log(a); // [100, 200, 300, 1, 2, 3, 4, 5, 6, 7, 8]
reverse()會將數組反轉。
使用push()后會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
a.reverse();
console.log(a); // [8, 7, 6, 5, 4, 3, 2, 1]
splice()可以移除或新增數組的元素,它包含了三個參數,第一個是要移除或要添加的序列號碼 (必填),第二個是要移除的長度 ( 選填,若不填則第一個號碼位置后方的所有元素都會被移除,若設定為 0 則不會有元素被移除 ),第三個是要添加的內容 ( 選填 )
使用splice()后會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
a.splice(5,1);
console.log(a); // [1, 2, 3, 4, 5, 7, 8] ( 6 被移除了 )
設定第三個參數就能夠添加或替代元素。
let a=[1,2,3,4,5,6,7,8];
a.splice(5,1,100);
console.log(a); // [1, 2, 3, 4, 5, 100, 7, 8] ( 6 被移除,100 加到第 5 個位置 )
let b=[1,2,3,4,5,6,7,8];
b.splice(5,3,100,200,300);
console.log(b); // [1, 2, 3, 4, 5, 100, 200, 300] ( 6,7,8 被移除,100,200,300 加到第 5,6,7 個位置 )
let c=[1,2,3,4,5,6,7,8];
c.splice(5,0,100);
console.log(c); // [1, 2, 3, 4, 5, 100, 6, 7, 8] ( 沒有元素被移除,100 加到第 5 個位置 )
sort()可以針對數組的元素進行排序,里頭包含了一個排序用的判斷函數,函數內必須包含兩個參數,這兩個參數分別代表數組里第 n 個和第 n+1 個元素,通過比較第 n 和第 n+1 個元素的大小來進行排序。
使用sort()后會改變原本的數組內容。
let a=[1,3,8,4,5,7,6,2];
a.sort((x,y)=> y - x);
console.log(a); // [8, 7, 6, 5, 4, 3, 2, 1]
a.sort((x,y)=> x - y);
console.log(a); // [1, 2, 3, 4, 5, 6, 7, 8]
如果不使用判斷函數,默認會將元素轉換成字符串,并采用 unicode 來判斷,這也會造成某些數字的排序錯誤。
let a=[1,3,8,4,5,7,6,2,9,10,11];
a.sort();
console.log(a); // [1, 10, 11, 2, 3, 4, 5, 6, 7, 8, 9]
copyWithin()能復制數組中的某些元素,并將它們放到并取同一個數組指定的位置,copyWithin()有三個參數,第一個是要替換的位置 (必填),第二個是從什么位置開始復制 ( 選填,默認 0 ),第三個是停止復制的元素的前一個位置 ( 選填,默認等于數組長度 )。
使用copyWithin()后會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
a.copyWithin(2);
console.log(a); // [1,2,1,2,3,4,5,6] ( 因 7 和 8 超過數組長度,只出現到 6 )
let b=[1,2,3,4,5,6,7,8];
b.copyWithin(3,1,3);
console.log(b); // [1,2,3,2,3,6,7,8] ( 復制 2,3 替代 4,5 )
fill()會把數組中所有元素,替換為指定的值,fill()有三個參數,第一個是準備要替換的內容 (必填),第二個是從什么位置開始替換 ( 選填,不設定就全部替換 ),第三個是停止替換的元素的前一個位置 ( 選填,默認等于數組長度 )。
使用fill()會改變原本的數組內容。
let a=[1,2,3,4,5,6,7,8];
a.fill('a');
console.log(a); // ['a','a','a','a','a','a','a','a']
let b=[1,2,3,4,5,6,7,8];
b.fill('b',3,5);
console.log(b); // [1,2,3,'b','b',6,7,8]
length可以取得數組的長度 (所有元素的數量)。
let a=[1,2,3,4,5,6,7,8];
console.log(a.length); // 8
indexOf()會判斷數組中是否包含某個值,判斷的方式為「由左而右」,如果有包含就返回這個值在數組中的索引值,如果沒有就返回 -1,有兩個參數,第一個參數表示要判斷的值 (必填),第二個參數表示從數組的哪個位置開始判斷 ( 選填,默認為 0 )。
let a=[1,2,3,4,5,6,7,8];
console.log(a.indexOf(4)); // 3
console.log(a.indexOf(4,5)); // -1 ( 搜索 5,6,7,8 沒有 4 )
lastIndexOf()會判斷數組中是否包含某個值,判斷的方式為「由右而左」,如果有包含就返回這個值在數組中的索引值,如果沒有就返回 -1,有兩個參數,第一個參數表示要判斷的值 (必填),第二個參數表示判斷到數組的哪個位置 ( 選填,默認為整個數組長度 - 1 )。
let a=[1,2,3,4,5,6,7,8];
console.log(a.lastIndexOf(3)); // 2
console.log(a.lastIndexOf(3,1)); // -1 ( 只判斷 1,2,所以沒有 3 )
find()會將數組中的「每一個」元素帶入指定的函數內做判斷,并會返回第一個符合判斷條件的元素,如果沒有元素符合則會返回 undefined。
let a=[1,2,3,4,5,6,7,8];
console.log(a.find(e=> e > 3)); // 4
console.log(a.find(e=> e < 0)); // undefined
findIndex()會將數組中的「每一個」元素帶入指定的函數內做判斷,并會返回第一個符合判斷條件元素的位置號碼,如果沒有元素符合則會返回 -1。
let a=[1,2,3,4,5,6,7,8];
console.log(a.findIndex(e=> e > 3)); // 3
console.log(a.findIndex(e=> e < 0)); // -1
filter()會將數組中的「每一個」元素帶入指定的函數內做判斷,如果元素符合判斷條件則會返回,成為一個新的數組元素。
let a=[1,2,3,4,5,6,7,8];
console.log(a.filter(e=> e > 3)); // [4, 5, 6, 7, 8]
console.log(a.filter(e=> e%2==0)); // [2, 4, 6, 8]
forEach()會將數組中每個元素套用到指定的函數里進行運算,函數有三個參數,第一個參數表示每個元素的值 (必填),第二個參數為該元素的索引值 ( 選填 ),第三個參數則表示原本的數組 ( 選填 )。
let a=[1,2,3,4,5];
let b=0;
a.forEach(item=> {
b=b + item;
});
console.log(b); // 15 ( 1+2+3+4+5 )
如果通過第二和第三個參數搭配,就能做到改變原本數組的效果。
let a=[1,2,3,4,5];
a.forEach((item, index, arr)=> {
arr[index]=item * 10;
});
console.log(a); // [10,20,30,40,50]
join()可以將數組中所有元素,由指定的字符合并在一起變成字符串呈現,若沒有指定字符默認會用「逗號」合并。
let a=[1,2,3,4,5,6,7,8];
console.log(a.join()); // 1,2,3,4,5,6,7,8
console.log(a.join('')); // 12345678
console.log(a.join('@@')); // 1@@2@@3@@4@@5@@6@@7@@8
concat()可以將兩個數組合并在一起,如果是使用 ES6 語法也可以用擴展運算符...來代替。
let a=[1,2,3,4,5];
let b=[6,7,8,9];
let c=a.concat(b);
let d=[...a, ...b]; // 使用 ...
console.log(c); // [1,2,3,4,5,6,7,8,9]
console.log(d); // [1,2,3,4,5,6,7,8,9]
slice()可以截取出數組某部份的元素為一個新的數組,有兩個必填的參數,第一個是起始位置,第二個是結束位置 (操作時數字減 1)。
let a=[1,2,3,4,5,6,7,8];
let b=a.slice(2,4);
console.log(b); // [3, 4]
map()會處理數組中每個元素,最后返回出一個新的數組,里頭有一個函數 (必填) 和一個返回函數里的 this 參數 ( 選填 ),函數內又包含三個參數,第一個是每個元素的值 ( 必填 ),第二個是當前元素的索引值 ( 選填 ),第三個是當前的數組 ( 選填 )。
let a=[1,2,3,4,5,6,7,8];
let b=a.map(e=> {
return e + 10;
});
console.log(b); // [11, 12, 13, 14, 15, 16, 17, 18]
套用第二個和第三個參數的變化
let a=[1,2,3,4,5,6,7,8];
let b=a.map((e,i,arr)=> {
return `${e}${i}${arr.find(e=> e%5==1)}`; // 組合成「元素 + 索引值 + 除以五余數為 1 的元素」
});
console.log(b); // ['101', '211', '321', '431', '541', '651', '761', '871']
如果要使用返回函數里 this 的參數,則「不能使用」箭頭函數,因為箭頭函數的 this 指向和函數的 this 指向不同,所以要用一般的函數處理。
let a=[1,2,3,4,5,6,7,8];
let b=a.map(function(e){
return e + this; // 此處的 this 為 10
}, 10);
console.log(b); // [11, 12, 13, 14, 15, 16, 17, 18]
reduce()可以將數組中每個元素進行計算,每次計算的結果會再與下個元素作計算,直到結束為止,里頭包含一個函數 (必填) 和初始計算的數值 ( 選填 ),函數內有四個參數,第一個是計算的值 ( 必填 ),第二個是取得的元素 ( 必填 ),第三個是該元素的索引值 ( 選填 ),第四個是原本的數組 ( 選填 )。
let a=[1,2,3,4,5,6,7,8];
let b=a.reduce(function(total, e){
return total + e;
});
console.log(b); // 36 ( 1+2+3+4+5+6+7+8=36 )
reduceRight()和reduce()大同小異,只是其計算方式是由右到左,對于加法來說沒什么影響,但對于減法而言就有差異。
let a=[1,2,3,4,5,6,7,8];
let b=a.reduce(function(total, e){
return total - e;
});
console.log(b); // -34 ( 1-2-3-4-5-6-7-8=-34 )
let c=a.reduceRight(function(total, e){
return total - e;
});
console.log(c); // -20 ( 8-7-6-5-4-3-2-1=-20 )
flat()可以將一個多維數組的深度轉成一維 (扁平化),它有一個選填的參數,代表要轉換的深度數字,默認為 1,如果深度有很多層,可使用Infinity來全部展開成一維數組。
let a=[1,2,[3],[4,[5,[6]]]];
let b=a.flat();
let c=a.flat(2);
let d=a.flat(Infinity);
console.log(b); // [1, 2, 3, 4, [5, [6]]]
console.log(c); // [1, 2, 3, 4, 5, [6]]
console.log(d); // [1, 2, 3, 4, 5, 6]
flatMap()的方法等于map()和flat()的組合,在運算后直接將數組扁平化處理。
let a=[1,2,[3],[4,5]];
let b=a.flatMap(e=> e+1);
let c=a.map(e=> e+1).flat();
console.log(b); // [2, 3, "31", "4,51"] ( 可以看到 b 和 c 得到的結果相同 )
console.log(c); // [2, 3, "31", "4,51"]
Array.isArray()能判斷一個對象是否為數組,如果是就返回 true,不然就返回 false。
let a=[1,2,3,4,5,6,7,8];
let b=123;
let c='hello';
let d={d1:1,d2:2};
console.log(Array.isArray(a)); // true
console.log(Array.isArray(b)); // false
console.log(Array.isArray(c)); // false
console.log(Array.isArray(d)); // false
Array.from()會將「類數組對象」或是「可迭代的對象」轉換成數組,Array.from()有兩個參數,第一個參數為「類數組對象」或「可迭代的對象」(必填),第二個參數則是改變轉換成數組元素的函數 ( 選填 )。
類數組對象具有 length 屬性以及索引化 index 的元素,可迭代對象表示具有可以利用迭代的方式取得它自己本身的元素,例如 Map 和 Set... 等。(參考 MDN 說法)
let a='abcde';
let b=Array.from(a);
console.log(b); // ['a','b','c','d','e']
let c=Array.from(a, e=> e + e);
console.log(c); // ['aa','bb','cc','dd','ee']
類數組對象寫法必須包含 length 屬性,且對象 key 須為 0 開始的數字,對應轉換后的元素索引。
let a={
'0': 14,
'2': 13,
'1': 7,
'3': 9,
'4': 6,
length: 5
};
let b=Array.from(a);
console.log(b); // [14,7,13,9,6]
Array.of()可以快速將數字、字符串等內容,轉換成數組。
let a=Array.of(1,'a',2,'b',3);
console.log(a); // [1, "a", 2, "b", 3]
toString()會把整個數組轉換成文字。
let a=[1,2,3,4,5,6,7,8];
let b=a.toString();
console.log(b); // 1,2,3,4,5,6,7,8
every()會將數組中的「每一個」元素帶入指定的函數內做判斷,只要有任何一個元素不符合判斷條件,會返回 false,如果全部符合,就會返回 true。
let a=[1,2,3,4,5,6];
console.log(a.every(e=> e > 3)); // fasle ( 因為 1、2 小于 3,3 等于 3 )
console.log(a.every(e=> e > 0)); // true
some()會將數組中的「每一個」元素帶入指定的函數內做判斷,只要有任何一個元素符合判斷條件,就會返回 true,如果全都不符合,就會返回 false。
let a=[1,2,3,4,5,6];
console.log(a.some(e=> e > 3)); // 返回 true,因為 4、5、6 大于 3
console.log(a.some(e=> e > 6)); // 返回 fasle,因為全都小于或等于 6
includes()會判斷數組中是否包含某個值,如果有包含就返回 true,否則返回 false,有兩個參數,第一個參數表示要判斷的值 (必填),第二個參數表示從數組的哪個位置開始判斷 ( 選填 )。
let a=[1,2,3,4,5,6,7,8];
console.log(a.includes(2)); // true
console.log(a.includes(2,2)); // false ( 搜索 3,4,5,6,7,8 沒有 2 )
valueOf()會返回數組的原始值,如果原本的數組有修改,那么返回的原始值也會跟著改變
let a=[1,2,3,4,5,6,7,8];
let b=a.valueOf();
console.log(a); // [1, 2, 3, 4, 5, 6, 7, 8]
let c=a.valueOf();
a.shift();
console.log(a); // [2, 3, 4, 5, 6, 7, 8]
console.log(b); // [2, 3, 4, 5, 6, 7, 8] ( 因為 a 的原始值更動了,所以 b 也變了 )
console.log(c); // [2, 3, 4, 5, 6, 7, 8]
keys()會返回數組中的每一個索引值 (key) 成為一個新的 Array Iterator 對象,因為是 Array Iterator 對象,可以通過for...of來取得。
let a=['a','b','c','d','e'];
let b=a.keys();
for (let key of b) {
console.log(key); // 連續出現 1、2、3、4、5
}
javascript2
單個值添加到現有數組末尾:
var arr=["頭條", "@", "新浪潮"];
arr.push("添加我");
console.log(arr);
單個值添加到現有數組末尾
單個值添加到現有數組開頭:
var arr=["頭條", "@", "新浪潮"];
arr.unshift("添加我到頭部");
console.log(arr);
單個值添加到現有數組
多個值附加到數組末尾中:
var arr=["頭條", "@", "新浪潮"];
arr.push("添加我", "添加你");
console.log(arr);
多個值附加到數組中
let arr=["頭條", "@", "新浪潮"];
let waitToAdd=["添加我", "添加你"];
arr=arr.concat(waitToAdd);
console.log(arr);
let arr=["頭條", "@", "新浪潮"];
arr=[...arr, "添加我"];
console.log(arr);
es6 尾部加單項
let arr=["頭條", "@", "新浪潮"];
let waitToAdd=["添加我", "添加你"];
arr=[...arr, ...waitToAdd];
console.log(arr);
es6數組合并
說到JavaScript的數組,大家基本都能馬上想起pop()、push()、shift()、unshift()、indexof()等等,今天給大家分享幾個開發中常用的js數組方法。
1、filter()
語法:array.filter(function(currentValue,index,arr), thisValue)
參數說明:
currentValue:當前元素對象(必選)
index:當前元素的索引值(可選)
arr:當前元素屬于的數組對象(可選)
thisValue:對象作為該執行回調時使用,傳遞給函數,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值為 "undefined"(可選)
//過濾年齡大于10的元素
var ages=[5, 32, 7, 10, 33, 12, 40];
var res=ages.filter(function (currentValue) {
return currentValue > 10;
})
console.log(res.toString());
//輸出結果:32,33,12,40
//箭頭函數寫法
var res1=ages.filter(item=> item > 10)
console.log(res.toString());
//輸出結果:32,33,12,40
2、forEach()
語法:array.forEach(function(currentValue, index, arr), thisValue)
參數用法同上
//循環輸出每個參數
var ages=[5, 32, 7, 10, 33, 12, 40];
ages.forEach(function (currentValue, index) {
console.log("參數:" + currentValue + "索引:" + index);
})
//箭頭函數寫法
ages.forEach((item, index)=> {
console.log("參數:" + item + "索引:" + index);
})
再看下面一段代碼:
//把10修改成20
var ages=[5, 32, 7, 10, 33, 12, 40];
ages.forEach(function (currentValue, index) {
if (currentValue===10) {
ages[index]=20
return
}
console.log(index);
})
console.log(ages);
我們在代碼中將10的值改成20后,加了一個return,但是運行結果顯示還是打印了7次index的值,這就是forEach的一個缺點,只有循環結束才能停止。那如何解決呢?
3、some()
語法:array.some(function(currentValue,index,arr),thisValue)
參數用法同上
//把10修改成20
var ages=[5, 32, 7, 10, 33, 12, 40];
ages.some(function (currentValue, index) {
if (currentValue===10) {
ages[index]=20
return true
}
console.log(index);
})
console.log(ages);
//把10修改成20 箭頭函數
var ages=[5, 32, 7, 10, 33, 12, 40];
ages.some((item, index)=> {
if (item===10) {
ages[index]=20
return true
}
console.log(index);
})
console.log(ages);
上面的代碼中運行結果只會打印三次index的值,通過some就可以完美解決forEach()的不足,開發過程中就看大家的需要就行選擇。
4、every()
語法:array.every(function(currentValue,index,arr), thisValue)
參數用法同上
//判斷每個元素的值是否都大于4
var ages=[5, 32, 7, 10, 33, 12, 40];
var res=ages.some(function (currentValue) {
return currentValue > 4
})
console.log(res);
//輸出:true
//箭頭函數
var res=ages.some(item=> item > 4)
console.log(res);
5、reduce()
語法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
參數說明:
total:必需。初始值, 或者計算結束后的返回值。
currentValue: 必需。當前元素
currentIndex:可選。當前元素的索引
arr:可選。當前元素所屬的數組對象。
initialValue:可選。傳遞給函數的初始值
//計算所有元素的和
var numbers=[15.5, 2.3, 1.1, 4.7];
var res=numbers.reduce(function (total, currentValue) {
return total +=currentValue
}, 0)
console.log(res);
//23.6
//計算大于4的元素的和
var result=numbers.filter(item=> item > 4).reduce((total, item)=> total +=item, 0)
console.log(result);
//20.2
6、合并數組
*請認真填寫需求信息,我們會在24小時內與您取得聯系。