[Javascript] 陣列、陣列的操作

URL Link //n.sfs.tw/13211

2019-04-02 22:51:45 By 張○○

Javascript 的陣列操作,做個筆記

宣告

var arr=array();

var arr=[];

var arr=[1,5,66,7,2];

var arr=["a","ccc",234,6];

var arr2=new Array(40, 100, 1, 5, 25, 10); // 不建議寫法[4],不要用 new Array()來初始陣列

帶key name的陣列不建議使用,因為無法計算長度等問題[4]

var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length;     // person.length will return 0
var y = person[0];         // person[0] will return undefined

陣列取值

var a= arr[1];

var b= arr['ddd'];

 

陣列長度

var len= arr.length;

 

塞入項目

arr.push("fromlast");  //由後面置入

list[ list.length ] = "baz";  // 同上

arr.unshift("fromfirst");  //放最前面

 

移除項目[6]

切掉後面的項目,直接設定length

var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements ar= [1, 2, 3, 4]

拿掉最後

ar.pop();

拿掉第一個

ar.shift();

使用 splice(位置,個數)

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var removed = arr.splice(2,3);
/* removed === [3, 4, 5]
   arr === [1, 2, 6, 7, 8, 9, 0] */

 

把字串拆解為陣列

var arr=str.split(',');

 

把陣列組成為字串

var str=arr.join(',')

 

檢查是否為陣列[4]

Array.isArray(yourarray);   // returns true/false

 

檢查 key是否存在[2]

if (typeof arr[key] != "undefined"){ }  //陣列中的key為變數

if ("key" in arr){ }

 

陣列排序

arr.sort();  //由文字來排序,若要由值或自訂,請參考[5]

var array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1); // expected output: Array [1, 100000, 21, 30, 4]

 

參考資料

[1] https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/join

[2] https://stackoverflow.com/questions/2613192/check-if-an-array-item-is-set-in-js

[3] https://www.hostingadvice.com/how-to/javascript-add-to-array/

[4] https://www.w3schools.com/js/js_arrays.asp

[5] https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

[6] https://love2dev.com/blog/javascript-remove-from-array/