在JS數組指定位置插入元素

來源:互聯網
上載者:User

標籤:javascript   索引   數組   插入   prototype   

原文連結: Array: Insert an Item at a Specific Index with JavaScript
原文日期: 2014年07月24日
翻譯日期: 2014年07月26日
翻譯人員: 鐵錨

很多與數組有關的任務聽起來很簡單,但實際情況並不總是如此,而開發人員在很多時候也用不到他。最近我碰到了這樣一個需求: 將一個元素插入到現有數組的特定索引處。聽起來很容易和常見,但需要一點時間來研究它。

// 原來的數組var array = ["one", "two", "four"];// splice(position, numberOfItemsToRemove, item)// 拼接函數(索引位置, 要刪除元素的數量, 元素)array.splice(2, 0, "three");array;  // 現在數組是這個樣子 ["one", "two", "three", "four"]


如果你對擴充原生 JavaScript 不反感,那麼可以將這個方法添加到數組原型(Array prototype)中:
Array.prototype.insert = function (index, item) {  this.splice(index, 0, item);};

此時,可以這樣調用:
var nums = ["one", "two", "four"];nums.insert(2, ‘three‘); // 注意數組索引, [0,1,2..]array// ["one", "two", "three", "four"]

我對數組也進行過一些其他的修改,可能你已經看過了:
  • Remove an Item From an Array : 從數組中刪除元素
  • Clone Arrays : 數組複製
  • Empty Arrays : 空數組
  • Sort Arrays : 數組排序
Arrays 非常的有用—— JavaScript中處理某些任務還是比較繁瑣…… 必須編寫比實際需要的更多的代碼(code-heavy)。為了更方便,請收藏本文,或者將這些片段儲存到你的工具箱吧!

聯繫我們

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