有没有一种方法可以将字符串推到数组中每个元素的末尾(我必须使用while循环?

时间:2019-06-17 17:06:08

标签: 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循环为它们添加解释点。

4 个答案:

答案 0 :(得分:3)

您不需要concatenation而不是push,即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))

答案 1 :(得分:0)

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

function makeFactsExciting(array) {
  var i;

  for (i = 0; i < array.length; i++) {
    array[i] = array[i] + '!!!';
  }

  return array;
}

console.log( makeFactsExciting(facts) );

答案 2 :(得分:0)

如果不想创建新数组,可以使用 forEach 来修改原始数组,即使用map()时会发生什么:

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

facts.forEach((v, i) => facts[i] = `${v}!!!`);

console.log(facts);

答案 3 :(得分:0)

使用forEach(),您可以执行以下操作:

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

//Use a while loop to loop over the facts array and add "!!!" to the end of every fact. Return an array of strings with exclamation points.

function johnLennonFacts(array) {
 const result = []
  array.forEach((i) => {
    if (i) result.push(i+"!!!")
  })
  return result
}

console.log(johnLennonFacts(facts));