Il y a ici des réponses vraiment créatives à cette question. Voici une solution simple pour ceux qui débutent avec les tableaux. Il peut être conçu pour fonctionner jusqu'aux navigateurs compatibles ECMAScript 3, si vous le souhaitez.
Sachez quelque chose sur l'épissure avant de commencer.
Réseau de développeurs Mozilla: Array.prototype.splice ()
Tout d'abord, comprenez deux formes importantes de .splice()
.
let a1 = [1,2,3,4],
a2 = [1,2];
Méthode 1) Supprimez les éléments x (deleteCount), à partir d'un index souhaité.
let startIndex = 0,
deleteCount = 2;
a1.splice(startIndex, deleteCount); // returns [1,2], a1 would be [3,4]
Méthode 2) Supprimez les éléments après un index de début souhaité jusqu'à la fin du tableau.
a1.splice(2); // returns [3,4], a1 would be [1,2]
En utilisant .splice()
, un objectif pourrait être de se diviser a1
en tableaux tête et queue en utilisant l'une des deux formes ci-dessus.
En utilisant la méthode n ° 1, la valeur de retour deviendrait la tête et a1
la queue.
let head = a1.splice(startIndex, deleteCount); // returns [1,2], a1 would be [3,4]
Maintenant, d'un seul coup, concatène la tête, le corps ( a2
) et la queue
[].concat(head, a2, a1);
Ainsi, cette solution ressemble plus au monde réel qu'à toute autre présentée jusqu'à présent. N'est-ce pas ce que vous feriez avec Legos? ;-) Voici une fonction, réalisée en utilisant la méthode # 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]
Plus court:
/**
*@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));
}
Plus sûr:
/**
*@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));
}
Les avantages de cette solution incluent:
1) Une simple prémisse domine la solution - remplir un tableau vide.
2) La nomenclature de la tête, du corps et de la queue semble naturelle.
3) Pas de double appel à .slice()
. Aucun tranchage du tout.
4) Non .apply()
. Très inutile.
5) Le chaînage des méthodes est évité.
6) Fonctionne dans ECMAScript 3 et 5 simplement en utilisant var
au lieu de let
ou const
.
** 7) Assure qu'il y aura une tête et une queue à claquer sur le corps, contrairement à de nombreuses autres solutions présentées. Si vous ajoutez un tableau avant ou après les limites, vous devriez au moins utiliser .concat()
!!!!
Remarque: l'utilisation de l'opéateur d'étalement ...
rend tout cela beaucoup plus facile à accomplir.