简体   繁体   English

如何将特定数量的元素推入数组

[英]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").我想根据变量(“x”)在数组末尾推送一些空白元素。 If x = 3, it would add three elements to the end of the array:如果 x = 3,它将在数组末尾添加三个元素:

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

I know the push method allows you to add specific elements to the end of an array.我知道 push 方法允许您将特定元素添加到数组的末尾。 How would I achieve this?我将如何实现这一目标? Hope this question is clear希望这个问题很清楚

You could simply iterate the desired number of times and push undefined :您可以简单地迭代所需的次数并推送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:采取一个 for 循环这是你的答案,例如:

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 ] a = [ 1, 2, 3 ]

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

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

change 3 to any number you want将 3 更改为您想要的任何数字

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如果是 - 那么请随时阅读https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

.concat() would do the job .concat()会完成这项工作

 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, "", "", ""]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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