How to insert an item into an array at a specific index (JavaScript)

要插入值到array特定位置, 使用 .insert(idx,obj) 會顯示錯誤, 為什麼不這麼做, 很不直覺耶. 解法:
https://stackoverflow.com/questions/586182/how-to-insert-an-item-into-an-array-at-a-specific-index-javascript

You want the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it’s just an insert).

In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *