1. 程式人生 > >js 陣列的新增和刪除方法

js 陣列的新增和刪除方法

1. shift() 方法:把陣列的第一個元素刪除,並返回刪除的元素值。(會改變原陣列)

var movePos= [11,22]; movePos.shift() console.log(movePos)//[22] alert(movePos)//22

document.write(movePos.length);//1

2.concat() 方法:用於連線兩個或多個數組,並返回一個新陣列。(不會改變原陣列) 

var movePos=[11,22];

var arr=movePos.concat(4,5); console.log(arr);//[11, 22, 4, 5] alert(arr);//11, 22, 4, 5

var ar1=[2,3] var ar3=[1111,2222]; var ar2=arr.concat(ar1,ar3); console.log(ar2); //[11, 22, 4, 5, 2, 3, 1111, 2222] alert(ar2); //11, 22, 4, 5, 2, 3, 1111, 2222

document.write(arr.length);//4

document.write(ar2.length);//8

 3. join() 方法:把陣列中的元素放入一個字串。元素是通過指定的分隔符進行分隔的。

返回一個字串。該字串是通過把 arrayObject 的每個元素轉換為字串,然後把這些字串連線起來,在兩個元素之間插入separator

 字串而生成的。

var movePos=[11,22];

var arr=movePos.join("+"); document.write(arr)  //11+22

4. pop() 方法:把陣列最後一個元素刪除,並返回最後一個元素的值, 如果陣列為空則返回undefined。(會改變原陣列)

var movePos=[11,22,33]; var arr= movePos.pop(); document.write(arr)  //33

document.write(arr.length)//2  

5.push() 方法:向陣列末尾新增一個或多個元素,並返回陣列長度。(會改變原陣列)

var movePos=[11,22];

var arr= movePos.push("333");

document.write(arr)  //返回的結果就是陣列改變後的長度:3

document.write(arr.length)  //undefined

6.reverse() 方法:用於顛倒陣列元素的順序,返回新的陣列。

var movePos=[11,22];

var arr=movePos.reverse();

document.write(arr)  //返回新的陣列:22,11

document.write(arr.length)  //返回陣列長度2

7.slice() 方法:從陣列擷取的元素,返回擷取的元素 slice(開始位,結束位)。

var movePos=[11,22,33];

var arr= movePos.slice(1,2); //(開始位, 結束位);

document.write(arr)  //返回擷取的元素:22

document.write(arr.length)  //返回陣列長度1,擷取的陣列的長度

8.splice() 方法:向/從陣列新增/刪除專案,返回新的陣列。(會改變原陣列) ???????

var movePos=[11,22,33,44];

var arr= movePos.splice(1,2);  //movePos.splice(開始位, 刪除的個數);

document.write(arr) ; //返回新的陣列:[22,11]

document.write(arr.length) ;//返回陣列長度2

    var movePos =[111,222,333,444];

    movePos.splice(2,1,"666") //movePos.splice(開始位, 刪除元素的個數,向陣列新增的新專案。);從下標2開始刪除一位,並用666替換刪除下表位置的元素     document.write(movePos + "<br />")  //[111,222,"666",444];

9.unshift() 方法:從陣列的開頭新增一個或更多元素,並返回陣列的長度 

var movePos =[111,222,333,444]; movePos.unshift("55555") document.write(movePos + "<br />")//55555,111,222,333,444

10.sort(orderfunction):按指定的引數對陣列進行排序 var movePos =["444","111","333","222"];

movePos.sort(1)

document.write(movePos + "<br />")//55555,111,222,333,444