javascript 如何在 JS 数组的所有元素之间插入一个新元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46528616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a new element in between all elements of a JS array?
提问by Philippe
I have an array [a, b, c]. I want to be able to insert a value between each elements of this array like that: [0, a, 0, b, 0, c, 0].
我有一个数组[a, b, c]。我希望能够给此阵列的像的各元件之间的插入值:[0, a, 0, b, 0, c, 0]。
I guess it would be something like this, but I can't make it works.
我想它会是这样的,但我不能让它工作。
for (let i = 0; i < array.length; i++) {
newArray = [
...array.splice(0, i),
0,
...array.splice(i, array.length),
];
}
Thank you for helping me!
感谢你们对我的帮助!
采纳答案by Nina Scholz
For getting a new array, you could concat the part an add a zero element for each element.
为了获得一个新数组,您可以连接该部分并为每个元素添加一个零元素。
var array = ['a', 'b', 'c'],
result = array.reduce((r, a) => r.concat(a, 0), [0]);
console.log(result);
Using the same array
使用相同的数组
var array = ['a', 'b', 'c'],
i = 0;
while (i <= array.length) {
array.splice(i, 0, 0);
i += 2;
}
console.log(array);
A bit shorter with iterating from the end.
从最后开始迭代会更短一些。
var array = ['a', 'b', 'c'],
i = array.length;
do {
array.splice(i, 0, 0);
} while (i--)
console.log(array);
回答by Vincent Menant
Another way if you want to exclude the start and end of array is :
如果要排除数组的开头和结尾,另一种方法是:
var arr = ['a', 'b', 'c']
var newArr = [...arr].map((e, i) => i < arr.length - 1 ? [e, 0] : [e]).reduce((a, b) => a.concat(b))
console.log(newArr)
回答by Nenad Vracar
You can use map()with ES6 spread syntax and concat()
您可以使用map()ES6 扩展语法和concat()
var arr = ['a', 'b', 'c']
var newArr = [0].concat(...arr.map(e => [e, 0]))
console.log(newArr)
回答by Pako Navarro
Another way:
其他方式:
var a = ['a', 'b', 'c'],
b;
b = a.reduce((arr, b) => [...arr, b, 0], []);
console.log(b);
回答by JLRishe
You could use .reduce():
你可以使用.reduce():
function intersperse(arr, val) {
return arr.reduce((acc, next) => {
acc.push(next);
acc.push(val);
return acc;
}, [val]);
}
console.log(intersperse(['a', 'b', 'c'], 0));
Or to accomplish this by modifying the original array:
或者通过修改原始数组来完成此操作:
function intersperse(arr, val) {
for (let i = 0; i <= arr.length; i += 2) {
arr.splice(i, 0, val);
}
return arr;
}
console.log(intersperse(['a', 'b', 'c'], 0));
回答by Cody Fortenberry
It could be done with strings by splitting and joining.
它可以通过拆分和加入字符串来完成。
var arr = ['a', 'b', 'c'];
var newArray = ("0," + arr.toString().split(",").join(",0,")).split(",");
console.log(newArray);
回答by Redu
This looks like the intersperse algorithmbut does some addition to the head and tail as well. So i call it extrasperse.
这看起来像散布算法,但也对头部和尾部进行了一些添加。所以我称之为extrasperse。
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
extrasperse = (x,a) => a.reduce((p,c,i) => (p[2*i+1] = c, p), Array(2*a.length+1).fill(x));
console.log(JSON.stringify(extrasperse("X",arr)));
回答by cн?dk
You just need to loop over the array elements and add the new element in each iteration, and if you reach the last iteration add the new element after the last item.
您只需要遍历数组元素并在每次迭代中添加新元素,如果到达最后一次迭代,则在最后一项之后添加新元素。
This is how should be your code:
这是您的代码应该如何:
var arr = ['a', 'b', 'c'];
var results = [];
arr.forEach(function(el, index) {
results.push(addition);
results.push(el);
if (index === arr.length - 1)
results.push(addition);
});
Demo:
演示:
This is a Demo snippet:
这是一个演示片段:
var arr = ['a', 'b', 'c'];
var results = [];
var addition = 0;
arr.forEach(function(el, index) {
results.push(addition);
results.push(el);
if(index === arr.length -1)
results.push(addition);
});
console.log(results);
回答by ibrahim mahrir
function insert(arr, elm) {
var newArr = [];
for(var i = 0; i < arr.length; i++) { // for each element in the array arr
newArr.push(elm); // add the new element to newArr
newArr.push(arr[i]); // add the current element from arr
}
newArr.push(elm); // finally add the new element to the end of newArr
return newArr;
}
console.log(insert(["a", "b", "c"], 0));
回答by Yangshun Tay
let arr = ['a', 'b', 'c'];
function insert(items, separator) {
const result = items.reduce(
(res, el) => [...res, el, separator], [separator]);
return result;
}
console.log(insert(arr, '0'));

