首页 > 解决方案 > 有没有办法将字符串推送到数组中每个元素的末尾(我必须使用 while 循环?

问题描述

创建一个函数 johnLennonFacts。

这个函数将接受一个参数,一组关于约翰列侬的事实(请注意,它可能不完全是以下事实):

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"
];

使用 while 循环遍历事实数组并添加“!!!” 到每一个事实的结尾。返回带有感叹号的字符串数组。

function johnLennonFacts(array) {

    let i = 0;
    while (i < (0, array.length, i++)) {
        array.push('!!!');
    }
    return array;
}

我一直返回原始数组,但我需要通过 while 循环向它们添加解释点。

标签: javascriptarrayswhile-loop

解决方案


您不需要concatenationpush即向push数组添加一个新元素,而您所需的输出需要!!!在元素末尾添加(连接),所以使用string concatenation

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"
];

const final = facts.map(e=> e + '!!!')

console.log(final)

您的原始代码可以更改为

function johnLennonFacts(array) {
  let i = 0;
  let newArray = []
  while (i < array.length) {
    newArray.push(array[i] + ' !!!')
    i++
  }
  return newArray;
}

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"
];

console.log(johnLennonFacts(facts))


推荐阅读