Array=[3,4,5,6,7,6,7]
Temp=[1,2]
how to store the value of temp in the array's 5th and 6th index in JavaScript
Use the array.splice function arr.splice(index, 0, item);
will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).
This in combination with ...array to insert the values of the array instead of the array itself
let Array=[3,4,5,6,7,6,7]; console.log(Array); let Temp=[1,2] Array.splice(5, 0, ...Temp); console.log(Array);
Refering this article
splice
not only deletes items. You can also use it to insert items into the array. To effectively "spread" temp
, you need the spread operator :
array.splice(5, 0, ...temp);
Then you can reuse splice
to delete the old items:
array.splice(7, 2);
You could use splice
, but it would mutate your original array
For safer use, make the result in the whole new array without affecting the original one, here I suggest using slice
const array=[3,4,5,6,7,6,7] const temp=[1,2] const res = [array.slice(0, 5), temp, array.slice(5)].flat() console.log(res)
const arr = [3,4,5,6,7,6,7]; const temp = [1, 2]; const res = [...arr.slice(0, 5), ...temp, ...arr.slice(5)]; console.log(res);
You can destructure the first part from your array until index 5 and the rest like this, you don't need to use .flat()
to flatten the array.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.