jquery - Comment insérer un élément dans un tableau à un index spécifique (JavaScript)

Mots clés : javascriptjqueryarraysjavascript

meilleur 5 Réponses jquery - Comment insérer un élément dans un tableau à un index spécifique (JavaScript)

vote vote

99

var arr = []; arr[0] = "Jani"; arr[1] = "Hege"; arr[2] = "Stale"; arr[3] = "Kai Jim"; arr[4] = "Borge";  console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge arr.splice(2, 0, "Lene"); console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge
vote vote

84

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' ] 
vote vote

80

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]
vote vote

62

/* 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; }; 
["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6); // ["b", "X", "Y", "Z", "c"] 
/* 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" 
vote vote

58

function insertAt(array, index) {     var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);     return insertArrayAt(array, index, arrayToInsert); }  function insertArrayAt(array, index, arrayToInsert) {     Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));     return array; } 
// if you want to insert specific values whether constants or variables: insertAt(arr, 1, "x", "y", "z");  // OR if you have an array: var arrToInsert = ["x", "y", "z"]; insertArrayAt(arr, 1, arrToInsert); 

Questions similaires