A better way to splice an array into an array in javascript
有没有比这更好的方式在javascript中将数组拼接到另一个数组中
var string = 'theArray.splice('+start+', '+number+',"'+newItemsArray.join('","')+'");';
eval(string);
You can use apply to avoid eval:
var args = [start, number].concat(newItemsArray);
Array.prototype.splice.apply(theArray, args);
The apply function is used to call another function, with a given context and arguments, provided as an array, for example:
If we call:
var nums = [1,2,3,4];
Math.min.apply(Math, nums);
The apply function will execute:
Math.min(1,2,3,4);
Wrap that into a function and you get this:
function insertArrayAt(array, index, arrayToInsert) {
Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
}
You would use it like this:
var arr = ["A", "B", "C"];
insertArrayAt(arr, 1, ["x", "y", "z"]);
alert(JSON.stringify(arr)); // output: A, x, y, z, B, C
You can check it out in this jsFiddle: http://jsfiddle.net/luisperezphd/Wc8aS/
You can also add such a function to the Array prototype, if you want something that is almost identical to the splice method. Eg
Array.prototype.spliceArray = function(index, n, array) {
return Array.prototype.splice.apply(this, [index, n].concat(array));
}
Then usage would simply be:
var array = ["A","B","C","","E","F"];
array.splice(3,1,"D");
// array is ["A","B","C","D","E","F"]
array.spliceArray(3,3,["1","2","3"]);
// array is ["A","B","C","1","2","3"]
See it in action here: http://jsfiddle.net/TheMadDeveloper/knv2f8bb/1/
Some notes:
splice
function modifies the array directly, but returns the an array of elements that were removed... not the spliced array. Array
won't work in cases where specialized array classes are used, such as an ImageData data Uint8ClampedArray. 上一篇: UTC和GMT标准时间在.NET中的区别