javascript:常用數組操作

來源:互聯網
上載者:User

標籤:

concat()方法 數組和數組的 粘結:

var a=[1,2,3,4];

var b=[5,6,7,8];

var c=a.concat(b);

console.log(c); // [1,2,3,4,5,6,7,8] 

 

 

join()方法  改變數組中拼接的符號:

var a=[1,2,"字串",false,undefied,null];

a.join("++");  //   [1++2++字串++false++++];

 

undefined null 自動過濾掉了

 

 

 

push()方法 在數組的最後一項後追加數值。 //返回數組的長度

var a=[1,2,3]

a.push(9);  //返回數組的長度 4,改變了原數組

console.log(a) //[1,2,3,9]

向a數組中 push入 一個數組,push的數組會變為 a的子數組,a的長度+1 

 

pop() 刪除數組的最後一項。 //返回被刪除的值,改變了原數組

var a=[1,2,3,4];

a.pop()   // 返回刪除值 4

console.log(a)  // [1,2,3]

 

 

unshift() 在數組的第0項前 插入值,原數組的值索引向後移  //返回數組的長度,插入的值為數組,變為 子數組。 改變原數組

var a=[1,2,3];

a.unshift("wo");  //返回數組的長度 4

console.log(a);  //["wo",1,2,3]

var b=[9,8,7];

a.unshift(b);  //返回數組的長度 5;

console.log(a)  //[ [9,8,7] ,"wo",1,2,3] 

 

 

shift() 刪除數組的第0項,原數組的值 索引向前的移動。 //返回被刪除的值 改變原數組

var a=[1,2,3];

a.shift()  //返回被刪除的值 1;

console.log(a)  //[2,3]

 

 

reverse()  數組的值翻轉。 //返回 翻轉後的 數組 ,原數組改變

var a=[1,2,3];

a.reverse()  //[3,2,1]

 

 

slice(index,[end]) end可選   賦值索引從index開始到 end-1 結束 為一個新數組,原數組不變。

var a=[1,2,3,4,5];

a.slice(2,4) //返回 [3,4]

a.slice(0) //[1,2,3,4,5]

a.slice(3) //[4,5] 

console.log(a)  // [1,2,3,4,5]

 

sort()  按照 ASCII表排序  返回排序後新數組  原數組改變

var a=[1,2,3,12,13];

a.sort()  //返回 [1,12,13,2,3]

如果按照正常邏輯排序 :

a.sort(function(a,b){

   return a-b;

})    //[1,2,3,12,13]

 

 

splice(index,num,ele1,ele2...) 很強大的一個方法。index指 從index刪除(包括index對應的值) num指 刪除的個數, ele1,ele2...代表插入的值  //返回刪除的值 

原數組改變

 

var a=[1,2,3,4,5];

a.splice(1,2,"我是","插入的值")   //返回 刪除的值 2,3

console.log(a)  //  [1,"我是","插入的值",4,5]

 

 

javascript:常用數組操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.