前言 : 

因為最近瘋狂的用 javascript 操作 JSON,發現陣列實在是超級無敵好用

不管是在陣列上的資料儲存、過濾、排序、組合都超級好用

所以有整理了一些常用 + 日後可能會用到的操作方式

完整的 Array 用法可以看 MDN 官網

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

這篇只是列出來比較常用或可能會用到的操作

讓自己日後比較方便查~

 

ps : 

有些操作方法是定義在 ECMAScript 5 中

如果要在很舊的瀏覽器中使用可以自行定義在 Array.prototype 裡面

 

join : 將陣列元素用固定符號串成字串 (常用)

var arr = ["jack", "john", "may", "su", "Ada"];

var str = arr.join("、");

ANS:

str 為 jack、john、may、su、Ada

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

 

清除或增加陣列長度 (清除陣列很好用)

var arr = [1, 2, 3, 4, 5, 6];

arr.length = 2;

ANS:

[1,2]

arr.length = 0;

ANS:

[]

arr.length = 5;

ANS:

[,,,,]

 

刪除陣列元素

var arr = [1, 2, 3, 4, 5, 6];

delete arr[1];

ANS:

[1,,3, 4, 5, 6]

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

 

Array.form : 將字串或輸入參數組成陣列 (非常方便)

MDN 範例 : 

Array-like object (arguments) to Array

(function () {

var args = Array.from(arguments);

return args;

})(1, 2, 3); 

ANS:

[1, 2, 3]


Any iterable object...

Array.from(new Set(["foo", window]));

ANS:

["foo", window]


Map

var m = new Map([[1, 2], [2, 4], [4, 8]]);

Array.from(m);

ANS:

[[1, 2], [2, 4], [4, 8]]


Strings are both array-like and iterable

Array.from("foo");  //<-- 超方便

ANS:

["f", "o", "o"]


Using an arrow function as the map function to

manipulate the elements

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

ANS:

[2, 4, 6]


Generate a sequence of numbers

Array.from({length:5}, (v, k) => k);

ANS:

[0, 1, 2, 3, 4]

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

 

sort : 陣列排序 (很好用)

var arr = [5, 9, 1, 3, 2, 6];

arr.sort();

ANS:

[1,2,3,5,6,9]

//也可以這樣寫

arr.sort(function (a,b) {

return a - b;

})

ANS:

[1,2,3,5,6,9]

 

//如果要反過來排序的話

arr.sort(function (a,b) {

return b - a;

})

ANS:

[9,6,5,3,2,1]

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

 

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);

ANS:

(透過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

 

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

array.splice(index , howMany[, element1[, ...[, elementN]]])

參數

index : 要從哪個索引位置開始改變

howMany : 用來指出要移除多少個元素. 如果 howMany 等於 0,則沒有任何元素被移除

element1, ..., elementN : 要加入陣列的元素,如果省略則表示不加入只刪除

官網範例 : 

var myFish = ["angel", "clown", "mandarin", "surgeon"];

//removes 0 elements from index 2, and inserts "drum"

var removed = myFish.splice(2, 0, "drum");

//myFish is ["angel", "clown", "drum", "mandarin", "surgeon"]

//removed is [], no elements removed

//removes 1 element from index 3

removed = myFish.splice(3, 1);

//myFish is ["angel", "clown", "drum", "surgeon"]

//removed is ["mandarin"]

//removes 1 element from index 2, and inserts "trumpet"

removed = myFish.splice(2, 1, "trumpet");

//myFish is ["angel", "clown", "trumpet", "surgeon"]

//removed is ["drum"]

//removes 2 elements from index 0, and inserts "parrot", "anemone" and "blue"

removed = myFish.splice(0, 2, "parrot", "anemone", "blue");

//myFish is ["parrot", "anemone", "blue", "trumpet", "surgeon"]

//removed is ["angel", "clown"]

//removes 2 elements from 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

 

concat : 會將兩個陣列合併產生新的陣列,原陣列不改變 (不常用,但很簡單就記一下吧)

var alpha = ["a", "b", "c"];

var numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);

ANS:

["a", "b", "c", 1, 2, 3]

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

 

some : 陣列比對,只要有一個元素是 true,就返回 true (很好用)

var arr = ["jack", "john", "may", "su", "Ada"];

var flag = arr.some(function (value, index, array) {

return value == "may" ? true : false;

});

ANS:

flag 為 true

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

 

every :  陣列比對,所有元素都是 true 才是 true (很好用)

var arr = ["jack", "john", "may", "su", "Ada"];

var flag = arr.every(function (value, index, array) {

return value.length > 2;

});

ANS:

flag 為 false

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

 

filter : 陣列過濾,透過 filter 的過濾條件返回一個新陣列 (非常好用)

var arr = ["jack", "john", "may", "su", "Ada"];

var arr2 = arr.filter(function (value) {

return value.length > 3;

});

arr2.join("、");

ANS:

jack、john

 

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

var arr = [1, 2, 3, 4, 5, 6];

var arr2 = arr.map(function (element,index,array) {

return element * 2;

});

arr2.join("、");

ANS:

2、4、6、8、10、12

 MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

 

reduce : 陣列中的每一個元素都會呼叫一次callback函數,唯一不同的是,函數的回傳值會當作下一次呼叫的傳入值,方向為索引 0 到 陣列尾端 (冷門,幾乎可以不用記)

var arr = [1, 2, 3, 4, 5, 6];

var flag = arr.reduce(function (previousValue, currentValue, index, array) {

return previousValue + currentValue;

})

ANS:

所以 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

 

 

 

再來是幾個專案上有用到有關陣列的函數,都網路上人家寫好的拿來用 (有些也忘記出處)

陣列的 distinct : 取得陣列中不重複的元素值,輸出成新陣列 (有用到 jQuery)

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;

}

 

移除陣列中,指定的元素值之項目 (我都看不懂我在寫什麼)

出處 : Remove item from array by value

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');

ANS:

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');

ANS:

three,eleven

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 小雕 的頭像
    小雕

    小雕雕的家

    小雕 發表在 痞客邦 留言(1) 人氣()