javascript - unshift用法 - 如何在特定索引處將項插入數組?
splice js用法 (8)
我正在尋找一個Javascript數組插入方法,風格為:
arr.insert(index, item)
最好是在jQuery中,但任何Javascript實現都會在這一點上完成。
自定義數組insert
方法
1.有多個論點和鏈接支持
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
this.splice.apply(this, [index, 0].concat(
Array.prototype.slice.call(arguments, 1)));
return this;
};
它可以插入多個元素(如本機splice
所做)並支持鏈接:
["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]
2.使用數組類型參數合併和鏈接支持
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
index = Math.min(index, this.length);
arguments.length > 1
&& this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
&& this.insert.apply(this, arguments);
return this;
};
它可以將參數中的數組與給定數組合併,並且還支持鏈接:
["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"
在特定索引處附加單個元素
//Append at specific position(here at index 1)
arrName.splice(1, 0,'newName1');
//1: index number, 0: number of element to remove, newName1: new element
//Append at specific position (here at index 3)
arrName[3] = 'newName1';
在特定索引處附加多個元素
//Append from index number 1
arrName.splice(1, 0,'newElemenet1', 'newElemenet2', 'newElemenet3');
//1: index number from where append start,
//0: number of element to remove,
//newElemenet1,2,3: new elements
即使已經回答了這個問題,我還是將這個說明添加到另一種方法中。
我想將一個已知數量的項放入一個數組中,放入特定的位置,因為它們來自一個“關聯數組”(即一個對象),根據定義,它不能保證按排序順序排列。 我希望得到的數組是一個對像數組,但由於數組保證了它們的順序,所以對像在數組中按特定的順序排列。 所以我這樣做了。
首先是源對象,從PostgreSQL檢索的JSONB字符串。 我想讓它按每個子對像中的“order”屬性排序。
var jsonb_str = '{"one": {"abbr": "", "order": 3}, "two": {"abbr": "", "order": 4}, "three": {"abbr": "", "order": 5}, "initialize": {"abbr": "init", "order": 1}, "start": {"abbr": "", "order": 2}}';
var jsonb_obj = JSON.parse(jsonb_str);
由於對像中的節點數是已知的,因此我首先創建一個具有指定長度的數組:
var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);
然後迭代對象,將新創建的臨時對象放入陣列中的所需位置,而不進行任何“排序”。
for (var key of Object.keys(jsonb_obj)) {
var tobj = {};
tobj[key] = jsonb_obj[key].abbr;
var position = jsonb_obj[key].order - 1;
sorted_array[position] = tobj;
}
console.dir(sorted_array);
另一種可能的解決方案,使用Array#reduce
。
var arr = ["apple", "orange", "raspberry"],
arr2 = [1, 2, 4];
function insert(arr, item, index) {
arr = arr.reduce(function(s, a, i) {
i == index ? s.push(item, a) : s.push(a);
return s;
}, []);
console.log(arr);
}
insert(arr, "banana", 1);
insert(arr2, 3, 2);
您可以通過執行以下Array.insert
來實現Array.insert
方法:
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
然後你就可以使用它:
var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
我推薦在這種情況下使用純JavaScript,在JavaScript中也沒有插入方法,但是我們有一個方法,它是一個內置的Array方法,它可以為你完成工作,它叫做splice ...
讓我們看看什麼是splice() ......
splice()方法通過刪除現有元素和/或添加新元素來更改數組的內容。
好的,想像我們下面有這個數組:
const arr = [1, 2, 3, 4, 5];
我們可以刪除3
這樣:
arr.splice(arr.indexOf(3), 1);
它將返回3,但如果我們現在檢查arr,我們有:
[1, 2, 4, 5]
到目前為止,這麼好,但我們如何使用splice向陣列添加新元素? 讓我們回到3 ...
arr.splice(2, 0, 3);
讓我們看看我們做了什麼......
我們再次使用拼接 ,但是這次對於第二個參數,我們傳遞0 ,意味著我們想要刪除沒有項目,但同時,我們添加第三個參數,即將在第二個索引處添加的3個...
您應該知道,我們可以同時刪除和添加 ,例如現在我們可以這樣做:
arr.splice(2, 2, 3);
這將刪除索引2處的2個項目 ,然後在索引2處添加3 ,結果將為:
[1, 2, 3, 5];
這顯示了拼接中的每個項目如何工作:
array.splice(start,deleteCount,item1,item2,item3 ......)
為了正確的函數編程和鏈接目的, Array.prototype.insert()
的發明是必不可少的。 實際上,如果它已經返回變異數組而不是完全沒有意義的空數組,那麼splice可能是完美的。 所以這就是它
Array.prototype.insert = function(i,...rest){
this.splice(i,0,...rest)
return this
}
var a = [3,4,8,9];
document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");
好吧,上面的Array.prototype.splice()
改變原始數組,有些人可能會抱怨“你不應該修改不屬於你的東西”,這可能也是正確的。 因此,為了公益,我想給另一個不會改變原始數組的Array.prototype.insert()
。 在這裡;
Array.prototype.insert = function(i,...rest){
return this.slice(0,i).concat(rest,this.slice(i));
}
var a = [3,4,8,9],
b = a.insert(2,5,6,7);
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
除了拼接之外,您可以使用這種方法,它不會改變原始數組,但會創建一個帶有添加項的新數組。 你應該盡可能避免變異。 我在這裡使用ES6傳播運營商。
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, newItem) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted item
newItem,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10)
console.log(result)
// [1, 10, 2, 3, 4, 5]
這可以用來添加多個項目,通過稍微調整函數來使用其餘運算符來處理新項目,並將其傳播到返回的結果中
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, ...newItems) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted items
...newItems,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10, 20)
console.log(result)
// [1, 10, 20, 2, 3, 4, 5]