[英]In ES5 Javascript, how do I add an item to an array and return the new array immediately, without using concat?
我經常遇到一種情況,我想通過一個(原子)操作將一個項目添加到數組中並返回該新數組。
['a', 'b'].push('c');
將無法使用,因為它會返回新的長度。
我知道以下代碼有效
['a', 'b'].concat(['c']);
但是我發現它很丑陋(將兩個數組組合在一起,只是將一個項目添加到第一個數組的末尾)。
我不能使用Array.splice()
因為它會修改原始數組(並返回刪除的項)。 Array.slice()
確實返回淺表副本,但是您不能添加新項目。
ES6
我知道您可以在es6
中使用
[...['a', 'b'], 'c']
但我正在尋找es5
解決方案
洛達
我可以使用lodash
只是要清楚
我知道這可以通過幾種不同的方式來實現(例如上面的Array.concat()
方法),但是我正在尋找一種直觀的簡單代碼,不會“濫用”其他運算符
我知道以下代碼有效
['a', 'b'].concat(['c']);
但是我發現它很丑陋( 將兩個數組組合在一起只是在第一個數組的末尾添加一個項目)。
可以給concat()
方法一個(或多個)值,而無需先將值封裝在數組中,例如:
['a', 'b'].concat('c'); // instead of .concat(['c']);
來自MDN (我的重點):
數組和/或值以連接成一個新數組。
除此之外,沒有使用擴展名和現有方法的選項有限。
有關如何擴展數組的示例(盡管這將返回當前數組):
Array.prototype.append = function(item) { this.push(item); return this }; var a = [1, 2, 3]; console.log(a.append(4))
(可選)按照@torazaburo建議創建一個簡單函數,該函數可以將array和item作為參數:
function append(arr, item) {
arr.push(item);
return arr;
}
或使用concat()
:
function append(arr, item) {
return arr.concat(item)
}
我可以為Array.prototype.insert()
提供兩種方法,這些方法使您可以從數組中的任何索引開始插入單個或多個元素。
1)修改其調用的數組並返回它
Array.prototype.insert = function(i,...rest){ this.splice(i,0,...rest) return this } var a = [3,4,8,9]; console.log(JSON.stringify(a.insert(2,5,6,7)));
以上代碼段的ES5兼容版本。
Array.prototype.insert = function(i){
this.splice.apply(this,[i,0].concat(Array.prototype.slice.call(arguments,1)));
return this;
};
2)不改變其調用的數組並返回一個新的數組
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));
以上代碼段的ES5兼容版本。
Array.prototype.insert = function(i){
return this.slice(0,i).concat(Array.prototype.slice.call(arguments,1),this.slice(i));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.