js數組操作方法

來源:互聯網
上載者:User

標籤:ref   bsp   一個   target   try   tostring   個數   range   others   

合并兩個數組 - concat()

合并三個數組 - concat()

用數組的元素組成字串 - join()

刪除數組的最後一個元素 - pop()

數組的末尾添加新的元素 - push()

將一個數組中的元素的順序反轉排序 - reverse()

刪除數組的第一個元素 - shift()

從一個數組中選擇元素 - slice()

數組排序(按字母順序升序)- sort()

數字排序(按數字順序升序)- sort()

數字排序(按數字順序降序)- sort()

在數組的第2位置添加一個元素 - splice()

轉換數組到字串 -toString()

在數組的開頭添加新元素 - unshift()

1. concat():當不傳參數的時候,複製當前數組 

var colors = ["red","green","blue"];var colors1 = colors.concat();    //當不傳參數的時候,複製當前數組console.log(colors1 );

--輸出: ["red", "green", "blue"]

  concat("",[]):當傳遞的是數組的時候,該方法會將這些數組中的每一項都添加到結果數組中,如果傳遞的不是數組,這些值會被簡單地添加到結果數組的末尾。

var colors2 = colors.concat("yellow",["black","brown"]);console.log(colors2 );

--輸出:["red", "green", "blue", "yellow", "black", "brown"]

var parents = ["Jani", "Tove"];var brothers = ["Stale", "Kai Jim", "Borge"];var children = ["Cecilie", "Lone"];var family = parents.concat(brothers, children);console.log(family);

--輸出:["Jani", "Tove", "Stale", "Kai Jim", "Borge", "Cecilie", "Lone"]

2.join() 數組元素轉換成字串(預設,分隔)

var fruits = ["Banana", "Orange", "Apple", "Mango"];var myFruits0 =fruits.join();console.log(myFruits0 );

--輸出:Banana,Orange,Apple,Mango

3.slice() 從一個數組中選擇元素,截取

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var myFruits1 =fruits.slice(1,3);
console.log(myFruits1 );

--輸出:["Orange", "Lemon"]

  如果參數中有一個負數,則用數組長度加上該數組來確定相應的位置。如果結束位置小於開始位置,則返回空數組。

4.像數組的中部添加、刪除、替換元素

(1)插入

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(2,0,"Lemon","Kiwi");
console.log(fruits);

--輸出: ["Banana", "Orange", "Lemon", "Kiwi", "Apple", "Mango"]

(2)刪除

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(2,2);console.log(fruits);

--輸出:["Banana", "Orange"]

(3)替換

var fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(2,0,"Lemon","Kiwi");console.log(fruits);

--輸出:["Banana", "Orange", "Lemon", "Kiwi", "Mango"]

 

js數組操作方法

聯繫我們

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