javascript - 有没有办法将字符串推到数组中每个元素的末尾(我必须使用 while 循环?

标签 javascript arrays while-loop

创建函数 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 循环向它们添加解释点。

最佳答案

您需要串联而不是push,即push向数组添加一个新元素,而您所需的输出需要添加(串联)!!! 在元素末尾,因此使用字符串连接

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))

关于javascript - 有没有办法将字符串推到数组中每个元素的末尾(我必须使用 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56635943/

相关文章:

javascript - 性能问题: Components library following the dot notation structure

javascript - 使用javascript在php代码中显示标签的值

arrays - 如何在swift 3中将数组添加到数组成员

c - 指向局部指针数组的全局指针

java - 当我尝试无休止地更新 JTextField 时,为什么我的程序会卡住?

javascript - NodeJS 中 requestAnimationFrame() 的服务器端实现

javascript - 我似乎无法弄清楚我的 CSS 问题

arrays - 如何展平自定义对象 [[CustomModel?]] 的数组?

c - 在 while 内部使用 OR 运算符

java - 如何将这两个 while 语句合并为一个?