【javascript】數組對象常用API

來源:互聯網
上載者:User
concat()

串連兩個或多個數組,並返回結果

var a = [1,2,3];  var b = a.concat(6,7);  console.log(a);  //[1,2,3]  console.log(b);  //[1,2,3,6,7]
join(str)

把數組的所有元素用str分隔,預設逗號分隔

var a = [1,2,3]  var b = a.join('|');  console.log(a);  //[1,2,3]  console.log(b);  //"1|2|3"
pop()

刪除並返回數組的最後一個元素的值

var a = [1,2,3];  var b = a.pop();  console.log(a);  //[1,2]  console.log(b);  //3
push()

向數組的末尾添加一個或更多元素,並返回新的數組長度

var a = [1,2,3];  var b = a.push('4','5');  console.log(a);  //[1,2,3,4,5]  console.log(b);  //5 
reverse()

反轉數組中元素的順序

var a = [1,2,3,4,5];  var b = a.reverse();  console.log(a);  //[5,4,3,2,1]  console.log(b);  //[5,4,3,2,1]
shift()

刪除並返回數組的第一個元素

var a = [1,2,3];  var b = a.shift();  console.log(a);  //[2,3]  console.log(b);  //1
slice(start,end)

從已有的數組中返回選定的元素

var a = [1,2,3,4,5];  var b = a.slice(0,-1);  var c = a.slice(1,3);  var d = a.slice(1);  var e = a.slice(2,-2);  var f = a.slice(3,1);  console.log(a);  //[1,2,3,4,5]  console.log(b);  //[1,2,3,4]  console.log(c);  //[2,3]  console.log(d);  //[2,3,4,5]  console.log(e);  //[3]  console.log(f);  //[]
sort(func)

按指定的參數對數組排序

註:func 必須返回一個值。

負值,第一個參數比第二個參數小,排在前面。

零,相等。

正值,第一個參數比第二個參數大,排在後面。

var a = [1,2,10,3];  var b = a.sort();  console.log(a);  //[1,10,2,3]  console.log(b);  //[1,10,2,3]  var num = function(x,y) {      return x - y;  }  var c = a.sort(num);  console.log(a);  //[1,2,3,10]  console.log(c);  //[1,2,3,10]
splice(start,deleteCount,val1,val2,···)

從一個數組中移除一個或多個元素,並在該位置插入新元素,返回所移除的元素

var a = [1,2,3,4,5];  var b = a.splice(2,2,7,8);  console.log(a);  //[1,2,7,8,5]  console.log(b);  //[3,4]
unshift(val1,val2,···)

將指定元素插入數組開始位置,並返回新的長度

var a = [1,2,3];  var b = a.unshift(-2,-1);  console.log(a);  //[-2,-1,1,2,3]  console.log(b);  //5
toString()

將數組的元素轉換為字串,並用逗號分隔,且串連起來

var a = [1,2,3,4,5];  var b = a.toString();  console.log(a);  //[1,2,3,4,5]  console.log(b);  //"1,2,3,4,5"
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.