Есть ли способ вставить строку в конец каждого элемента в массиве (я должен использовать цикл while? - PullRequest
2 голосов
/ 17 июня 2019

Создать функцию 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 ]

3 голосов
/ 17 июня 2019

Вам нужно 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))
0 голосов
/ 17 июня 2019

С 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));
0 голосов
/ 17 июня 2019

Вы можете использовать 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);
0 голосов
/ 17 июня 2019

Вы пытаетесь добавить новые элементы в массив при использовании 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) );
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...