遍历名称数组

时间:2018-09-09 20:04:27

标签: javascript arrays loops for-loop

let names = ['pete', 'dave', 'sara', 'toni', 'michael'];
let name = "";
let names2 = [];


// names[i][j]



console.log (names);
console.log (names2); 

我必须找到一种方法来逐个字母地遍历names数组,并使names2的输出成为购买同一个字母数组的同一数组。

到目前为止,我有这个:

for (let i = 0; i < names.length; i++) {
for (let j = 0; j < names[i].length; j++) {
    name += names[i][j];
    names2 += name;
    name = "";

console.log (names);
console.log (names2);

输出应为:

['pete', 'dave', 'sara', 'toni', 'michael']
['pete', 'dave', 'sara', 'toni', 'michael']

(第二个字母一个字母记下来,第一个只是我们在开始时设置的普通数组)

但是我得到的是:

['pete', 'dave', 'sara', 'toni', 'michael']
petedavesaratonimichael

有人可以帮助我吗?

let names = ['pete', 'dave', 'sara', 'toni', 'michael'];
let name = "";
let names2 = [];

for (let i = 0; i < names.length; i++) {
  for (let j = 0; j < names[i].length; j++) {
      name += names[i][j];
      names2 += name;
      name = "";
  }
}

console.log (names);
console.log (names2);

2 个答案:

答案 0 :(得分:2)

我不确定这是什么运动,但这是一个解决方案(无循环,但有Array.mapArray.reduce)。

let names = ['pete', 'dave', 'sara', 'toni', 'michael'];

const convert = (names) => names.map(name => Array.from(name).reduce((result, c) => `${result}${c}`, ''))

console.log(names);
console.log(convert(names));

在您的解决方案中,您可能通过使用重载的+=运算符将数组强制为字符串。添加元素时,应改用Array.pushArray.concat

答案 1 :(得分:0)

geom_jitter