简体   繁体   中英

How to push specific number of elements into array

I have an array like the one below.

let array = ["Sandy", 5, 2, 7]

I want to push a number of blank elements at the end of the array based on a variable ("x"). If x = 3, it would add three elements to the end of the array:

let array = ["Sandy", 5, 2, 7, , , ]

I know the push method allows you to add specific elements to the end of an array. How would I achieve this? Hope this question is clear

You could simply iterate the desired number of times and push undefined :

 function padArray(arr, num) { for (var i=0; i < num; ++i) { arr.push(undefined); } } var array = ["Sandy", 5, 2, 7]; console.log(array); padArray(array, 3); console.log(array);

take a for loop it's your answer, example:

var array=[your array]
for(x=0;x<length of your variable;x++){
   array.push(your values to push)
}

var a = [1,2,3]

a = [ 1, 2, 3 ]

var c = Array(...a,...Array(3).fill(null))

c = [ 1, 2, 3, null, null, null ]

change 3 to any number you want

If you want to be fancy one liner to achieve it could look like:

 let array = ["Sandy", 5, 2, 7] console.log([...array, ...(new Array(3))])

Are tree dots looks strange? If yes - then please feel free to read about https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

.concat() would do the job

 let array = ["Sandy", 5, 2, 7] let x = 3; array = array.concat(Array(x)); console.log(array);

var arr = ["Sandy", 5, 2, 7];
var  x = 3;
for(var i = 0 ; i < x ; i++){
arr.push("");
}

console.log(arr);

and result

["Sandy", 5, 2, 7, "", "", ""]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM