Javascript 常用的 Array

筆記常用的Array用法,可於 MDN 官網 看更完整。

1. join 將陣列元素用固定符號串成字串

var arr = ["jack", "john", "may", "su", "Ada"];
var str = arr.join("、");
//str 為 jack、john、may、su、Ada
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

2. 清除或增加陣列長度

var arr = [1, 2, 3, 4, 5, 6];
arr.length = 2;
//[1,2]
arr.length = 0;
//[]
arr.length = 5;
//[,,,,]

3. delete 刪除陣列元素

var arr = [1, 2, 3, 4, 5, 6];
delete arr[1];
//[1,,3, 4, 5, 6]
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

4. Array.form 將字串或輸入參數組成陣列

Array-like object (arguments) to Array
(function () {
var args = Array.from(arguments);
return args;
})(1, 2, 3);
//[1, 2, 3]
Any iterable object...
Array.from(new Set(["foo", window]));
//["foo", window]
Map
var m = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(m);
//[[1, 2], [2, 4], [4, 8]]
Strings are both array-like and iterable
Array.from("foo"); //
//["f", "o", "o"]
Using an arrow function as the map function to manipulate the elements
Array.from([1, 2, 3], x => x + x);
//[2, 4, 6]
Generate a sequence of numbers
Array.from({length:5}, (v, k) => k);
//[0, 1, 2, 3, 4]
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

5. sort 陣列排序

var arr = [5, 9, 1, 3, 2, 6];
arr.sort();
//[1,2,3,5,6,9]
arr.sort(function (a,b) {
return a - b;
})
//[1,2,3,5,6,9]
反過來排序
arr.sort(function (a,b) {
return b - a;
})
//[9,6,5,3,2,1]
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

6. push 新增元素或元素組到陣列

var arr = {
name: [],
data:[]
};
arr.name.push("jack");
arr.name.push("john");
arr.data.push({ weight: 60, height: 170 });
arr.data.push({ weight: 62, height: 175 });
JSON.stringify(arr);
透過JSON.stringify 返回的是字串,方便看結構所以用物件實字來表示
{
"name":["jack","john"],
"data":[{"weight":60,"height":170},{"weight":62,"height":175}]
}
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

7. splice 改變陣列內容,移除或新增元素

array.splice(index , howMany[, element1[, ...[, elementN]]])
參數
index : 要從哪個索引位置開始改變
howMany : 用來指出要移除多少個元素. 如果 howMany 等於 0,則沒有任何元素被移除
element1, ..., elementN : 要加入陣列的元素,如果省略則表示不加入只刪除
官網範例 :
var myFish = ["angel", "clown", "mandarin", "surgeon"];
移除 0 元素 從 index 2, 並加入元素 "drum"
var removed = myFish.splice(2, 0, "drum");
//myFish is ["angel", "clown", "drum", "mandarin", "surgeon"]
//removed is [], no elements removed
移除 1 元素 從 index 3
removed = myFish.splice(3, 1);
//myFish is ["angel", "clown", "drum", "surgeon"]
//removed is ["mandarin"]
移除 1 元素 從 index 2, 並加入元素 "trumpet"
removed = myFish.splice(2, 1, "trumpet");
//myFish is ["angel", "clown", "trumpet", "surgeon"]
//removed is ["drum"]
移除 2 元素 從 index 0, 並加入元素"parrot", "anemone" and "blue"
removed = myFish.splice(0, 2, "parrot", "anemone", "blue");
//myFish is ["parrot", "anemone", "blue", "trumpet", "surgeon"]
//removed is ["angel", "clown"]
移除 2 元素 從 index 3
removed = myFish.splice(3, Number.MAX_VALUE);
//myFish is ["parrot", "anemone", "blue"]
//removed is ["trumpet", "surgeon"]
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

8. concat 將兩個陣列合併產生新的陣列,原陣列不改變

var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
//["a", "b", "c", 1, 2, 3]
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

9. some 陣列比對,只要有一個元素是 true,就返回 true

var arr = ["jack", "john", "may", "su", "Ada"];
var flag = arr.some(function (value, index, array) {
return value == "may" ? true : false;
});
//flag 為 true
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

10. every 陣列比對,所有元素都是 true 才是 true

var arr = ["jack", "john", "may", "su", "Ada"];
var flag = arr.every(function (value, index, array) {
return value.length > 2;
});
//flag 為 false
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

11. filter 陣列過濾,透過 filter 的過濾條件返回一個新陣列

var arr = ["jack", "john", "may", "su", "Ada"];
var arr2 = arr.filter(function (value) {
return value.length > 3;
});arr2.join("、");
//jack、john

12. map 對陣列中的各元素進行操作,操作後的值會被寫入新陣列中並返回

var arr = [1, 2, 3, 4, 5, 6];
var arr2 = arr.map(function (element,index,array) {
return element * 2;
});
arr2.join("、");
//2、4、6、8、10、12
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

13. reduce 陣列中的每一個元素都會呼叫一次callback函數,唯一不同的是,函數的回傳值會當作下一次呼叫的傳入值,方向為索引 0 到 陣列尾端

var arr = [1, 2, 3, 4, 5, 6];
var flag = arr.reduce(function (previousValue, currentValue, index, array) {
return previousValue + currentValue;
})
//所以 flag 為 1 + 2 + 3 + 4 + 5 + 6 = 21
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
reduceRight 與 reduce 相同,只是是從陣列尾端到索引 0 的位置
MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

14. 陣列的 distinct : 取得陣列中不重複的元素值,輸出成新陣列

function GetUnique(inputArray) {
var outputArray = [];
for (var i = 0; i < inputArray.length; i++) {
if ((jQuery.inArray(inputArray[i], outputArray)) == -1) {
outputArray.push(inputArray[i]);
}
}
return outputArray;
}

15. 移除陣列中,指定的元素值之項目

Array.prototype.remove = function () {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
使用例子:
var ary = ['three', 'seven', 'eleven'];
ary.remove('seven');
//three,eleven
要注意的是這個方法是附加在 Array 的原型當中
所以你用下面這樣去跑,後面會多一個 remove
var content = "";
for (var key in ary) {
content += key + "\n";
}
如果不想定義在prototype,也可以把它寫成 function
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');
//three,eleven

參考文章來源

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.