js常用數組操作方法簡明總結

來源:互聯網
上載者:User

//javascript 中的數組分割var colors = ["red","green","blue"];//alert(colors.toString());alert(colors.join("|")); //返回結果是red|green|bluevar colors = ["red","green","blue",null];alert(colors.join("|"));//red|green|blue|//注意當數組裡面有值是null或者是undefined的時候 返回的結果是以空的字串表示的-------------------------------------------//數組刪除和添加var colors = ["red","green","blue"];//alert(colors.toString());colors.push("white","test");//返回的結果是數組的長度alert(colors.join("|"));//結果是red|green|blue|white|test//往數組的開頭添加元素var colors = ["red","green","blue","test"];var item = colors.unshift("first");//數組的開頭添加一個元素alert(colors.join("|"));//返回最後的數組//刪除元素var colors = ["red","green","blue","test"];var item = colors.pop();//返回刪除的選項結果testalert(colors.join("|"));//返回最後的數組結果red|green|blue//刪除開頭元素var colors = ["red","green","blue","test"];var item = colors.shift();//刪除數組的第一個選項alert(colors.join("|"));//返回最後的數組-------------------------------------------------//數組順序案例//順序顛倒var colors = ["red","green","blue","test"];colors.reverse();alert(colors);//結果是:test,blue,green,red//數組排序var values = [0,1,5,10,7];values.sort(compare);alert(values);//document.writeln(values);} function compare(value1,value2){if(value1<value2){return 1 ;}else if(value1>value2){return -1 ;}else return 0 ;} -----------------------------------------------------//向數組中添加數組 concat()方法var colors = ["color","red"];var colors2 = colors.concat(["ccc","bbbb"],'3333',['vvccxx',['oolll','lll']]);alert(colors2);//返回結果是:color,red,ccc,bbbb,3333,vvccxx,oolll,lll//slice()方法複製數組中的元素並不會破壞之前的元素var colors = ["color","red",'eeee','221111'];var colors2 = colors.slice(1);//從1開始進行複製alert(colors2);//結果是:red,eeee,221111var colors = ["color","red",'eeee','221111'];var colors2 = colors.slice(1,3);//從1開始進行複製到第3個位置結束alert(colors2);//結果是red,eeee---------------------------------------------------------------------//數組中刪除元素var a = [1,2,3,5,8];var r = a.splice(0,2); //刪除前2項alert(a);//結果是3,5,8var a = [1,2,3,5,8];var r = a.splice(1,1,100,200); //從第2個數開始刪除一項 然後插入100 200alert(a);//結果是1,100,200,3,5,8

聯繫我們

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