我有像我的var bar一样的数组,我想在数组中的每个第二位添加var test。
var test = "foo";
var bar = ["Wilson 1", "Wilson 2"];
var new = ["Wilson 1", "foo" "Wilson 2", "foo"];
我尝试使用concat但没有结果:
var new = bar.concat(test);
答案 0 :(得分:1)
这没有标准功能,所以你必须自己做。你会如何解决它?我会
修改强>
所有其他答案都很糟糕,我觉得有必要添加一个完整的例子:
const test = "foo";
const bar = ["Wilson 1", "Wilson 2"];
const newA = [];
for (const item of bar) {
newA.push(item, test);
}
答案 1 :(得分:1)
这可以通过简单的for循环来实现
var test = "foo";
var bar = ["Wilson 1", "Wilson 2"];
var newA = [];
for (var i = 0; i < bar.lenght; i ++) {
newA.push(bar[i]);
newA.push(test);
}
答案 2 :(得分:0)
您可以使用ES6的spread
运算符,array.prototype.concat
和array.prototype.map
:
var test = "foo";
var bar = ["Wilson 1", "Wilson 2"];
var result = [].concat(...bar.map(e => [e, test]));
console.log(result);
答案 3 :(得分:0)
您可以采用while
循环并将值拼接为每个第二项。
var item = "foo",
array = ["Wilson 1", "Wilson 2"],
i = 1;
while (i <= array.length) {
array.splice(i, 0, item);
i += 2;
}
console.log(array);
&#13;
或使用Array#reduce
var item = "foo",
array = ["Wilson 1", "Wilson 2"],
result = array.reduce((r, a) => r.concat(a, item), []);
console.log(result);
&#13;
答案 4 :(得分:0)
我解决了:
var new = bar.map((m, i) => (m).concat(new Array(test[i])));
答案 5 :(得分:0)
您可以使用.forEach()
:
var test = "foo";
var bar = ["Wilson 1", "Wilson 2"];
var newArr = [];
bar.forEach(el => newArr.push(el, test))
console.log(newArr)
答案 6 :(得分:-1)
您可以使用array#reduce
var test = "foo",
bar = ["Wilson 1", "Wilson 2"],
result = bar.reduce((r,v) => {
r.push(v, test);
return r;
},[]);
console.log(result);
答案 7 :(得分:-1)
使用.reduce
并在其中添加current element
和test
var test = "foo";
var bar = ["Wilson 1", "Wilson 2"];
var newArr = bar.reduce((acc, el) => acc.concat([el, test]) , []);
console.log(newArr);
&#13;