对于这个问题,这里有一些真正有创意的答案。对于刚开始使用数组的人来说,这是一个简单的解决方案。如果需要,它可以一直工作到兼容 ECMAScript 3 的浏览器。
在开始之前了解一些关于拼接的知识。
Mozilla Developer Network: Array.prototype.splice()
首先,了解.splice()的两种重要形式。
let a1 = [1,2,3,4],
a2 = [1,2];
方法 1) 从所需索引开始删除 x (deleteCount) 个元素。
let startIndex = 0,
deleteCount = 2;
a1.splice(startIndex, deleteCount); // returns [1,2], a1 would be [3,4]
方法 2) 删除数组末尾所需起始索引之后的元素。
a1.splice(2); // returns [3,4], a1 would be [1,2]
使用.splice(),目标可以是使用上述两种形式之一将a1 拆分为头和尾数组。
使用方法#1,返回值将成为头部,a1 是尾部。
let head = a1.splice(startIndex, deleteCount); // returns [1,2], a1 would be [3,4]
现在,一举将头部、身体 (a2) 和尾部连接起来
[].concat(head, a2, a1);
因此,与迄今为止提出的任何其他解决方案相比,此解决方案更像现实世界。这不是你会用乐高积木做的吗? ;-) 这是一个函数,使用方法 #2 完成。
/**
*@param target Array The array to be split up into a head and tail.
*@param body Array The array to be inserted between the head and tail.
*@param startIndex Integer Where to split the target array.
*/
function insertArray(target, body, startIndex)
{
let tail = target.splice(startIndex); // target is now [1,2] and the head
return [].concat(target, body, tail);
}
let newArray = insertArray([1, 2, 3, 4], ["a", "b"], 2); // [1, 2, "a", "b", 3, 4]
更短:
/**
*@param target Array The array to be split up into a head and tail.
*@param body Array The array to be inserted between the head and tail.
*@param startIndex Integer Where to split the target array.
*/
function insertArray(target, body, startIndex)
{
return [].concat(target, body, target.splice(startIndex));
}
更安全:
/**
*@param target Array The array to be split up into a head and tail.
*@param body Array The array to be inserted between the head and tail.
*@param startIndex Integer Where to split the target array.
*@throws Error The value for startIndex must fall between the first and last index, exclusive.
*/
function insertArray(target, body, startIndex)
{
const ARRAY_START = 0,
ARRAY_END = target.length - 1,
ARRAY_NEG_END = -1,
START_INDEX_MAGNITUDE = Math.abs(startIndex);
if (startIndex === ARRAY_START) {
throw new Error("The value for startIndex cannot be zero (0).");
}
if (startIndex === ARRAY_END || startIndex === ARRAY_NEG_END) {
throw new Error("The startIndex cannot be equal to the last index in target, or -1.");
}
if (START_INDEX_MAGNITUDE >= ARRAY_END) {
throw new Error("The absolute value of startIndex must be less than the last index.");
}
return [].concat(target, body, target.splice(startIndex));
}
此解决方案的优点包括:
1) 一个简单的前提支配着解决方案——填充一个空数组。
2) 头部、身体和尾部的命名感觉很自然。
3) 没有对.slice() 的双重调用。完全没有切片。
4) 没有.apply()。非常不必要。
5) 避免了方法链接。
6) 只需使用 var 而不是 let 或 const,即可在 ECMAScript 3 和 5 中工作。
**7) 与提出的许多其他解决方案不同,确保有头部和尾部可以拍打在身体上。如果您在边界之前或之后添加数组,您至少应该使用.concat()!!!!
注意:使用扩展运算符 ... 可以更轻松地完成所有这些操作。