首页 > 解决方案 > 使用 while 循环遍历数组

问题描述

我正在通过训练营实验室并在循环实验室中面临一些挑战。该练习要求创建一个接受一个参数的函数 - 一组事实。我必须使用 while 循环来遍历事实数组,添加!!!到每个事实的末尾,并返回带有感叹号的字符串数组。

const facts = [
  "He was the last Beatle to learn to drive",
  "He was never a vegetarian",
  "He was a choir boy and boy scout",
  "He hated the sound of his own voice"
];

function johnLennonFacts() {
  let i = 0;
  while (i <= facts.lenght) {
    i++;
    console.log(facts[i] + '!!!');
  }
  return facts
}

标签: javascriptarrayswhile-loop

解决方案


这是您想要实现的目标:

const facts = [
  "He was the last Beatle to learn to drive",
  "He was never a vegetarian",
  "He was a choir boy and boy scout",
  "He hated the sound of his own voice"
];

// With one argument (array of facts) it's better :p
function johnLennonFacts(facts) {
  let i = 0;
  const factsModified = [];
  while (i <= facts.length) {
    factsModified.push(facts[i] + '!!');
    i++;
  }

  return factsModified;
}


推荐阅读