每隔一个地方连接两个数组

时间:2018-02-23 09:27:06

标签: javascript arrays

我有像我的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);

8 个答案:

答案 0 :(得分:1)

这没有标准功能,所以你必须自己做。你会如何解决它?我会

  • 创建新阵列
  • 循环遍历旧数组(bar)
  • 对于bar的每次迭代,我都会在新数组中添加一个项目+你想要的字符串。

修改

所有其他答案都很糟糕,我觉得有必要添加一个完整的例子:

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.concatarray.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循环并将值拼接为每个第二项。

&#13;
&#13;
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;
&#13;
&#13;

或使用Array#reduce

&#13;
&#13;
var item = "foo",
    array = ["Wilson 1", "Wilson 2"],
    result = array.reduce((r, a) => r.concat(a, item), []);

console.log(result);
&#13;
&#13;
&#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 elementtest

&#13;
&#13;
var test = "foo";
var bar = ["Wilson 1", "Wilson 2"];

var newArr = bar.reduce((acc, el) => acc.concat([el, test]) , []);

console.log(newArr);
&#13;
&#13;
&#13;