數組的添加和刪除方法


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 ,把數組長度減 1

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

    splice() 方法可刪除從 index 處開始的零個或多個元素,並且用參數列表中聲明的一個或多個值來替換那些被刪除的元素。

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

    movePos.splice(2,1,"666")//movePos.splice(開始刪除的下表位置,刪除數組元素的個數,向數組添加的新項目。);從下標2開始刪除一位,並用666替換刪除下表位置的元素
    document.write(movePos + "<br />")

unshift() 方法可向數組的開頭添加一個或更多元素,並返回新的長度。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM