Я часами застрял в этой проблеме Twilioquest, и она включает в себя массивы. Как мне это решить? - PullRequest
0 голосов
/ 05 августа 2020

Итак, я недавно загрузил TwilioQuest, чтобы попытаться правильно изучить программирование. Все идет хорошо, и я думаю, что это отличная игра для изучения программирования, но я застрял в проблеме.

Чтобы перейти к следующей части игры, мне нужно создать программу, включающую функцию, которая принимает единственный аргумент командной строки массива и добавляет первый индекс массива к последнему. Он дал мне начальный код на случай, если он мне понадобится, но даже в этом я запутался. Это начальный код, который он мне дал:

function addFirstToLast(inputArray) {
  let firstAndLast = '';

  // Only execute this code if the array has items in it
  if (inputArray.length > 0) {
    // Change the line below! What should it be?
    firstAndLast = inputArray[999] + inputArray[999];
  }

  return firstAndLast;
}

// The lines of code below will test your function when you run it from the
// command line with Node.js
console.log(addFirstToLast(['first', 'second', 'third']));
console.log(addFirstToLast(['golden', 'terrier']));
console.log(addFirstToLast(['cheerio']));
console.log(addFirstToLast([]));

Я просто не понимаю, что мне нужно вставить в первые строки кода, где говорится, let firstAndLast = '';

Это то, что я добавил в код:

function addFirstToLast(inputArray) {
  let firstAndLast = inputArray[0] + inputArray[-1];

  // Only execute this code if the array has items in it
  if (inputArray.length > 0) {
    // Change the line below! What should it be?
    firstAndLast = inputArray[0] + inputArray[-1];
  }

  return firstAndLast;
}

// The lines of code below will test your function when you run it from the
// command line with Node.js
console.log(addFirstToLast(['first', 'second', 'third']));
console.log(addFirstToLast(['golden', 'terrier']));
console.log(addFirstToLast(['cheerio']));
console.log(addFirstToLast([]));

Однако он дает мне следующий результат:

firstundefined
goldenundefined
cheerioundefined
NaN

Кто-нибудь может мне помочь?

Ответы [ 2 ]

0 голосов
/ 05 августа 2020

добро пожаловать в Stack Overflow.

Я думаю, что строка кода, которую вы ищете, вот такая:

firstAndLast = inputArray[0] + inputArray[inputArray.length-1];

Это создаст строку со значением из первого элемента массива, соединенного со значением из последнего элемента массива (даже если они совпадают в случае длины 1). Первый оператор if предназначен для того, чтобы избежать ситуации передачи массива без элементов (как этот []).

0 голосов
/ 05 августа 2020

Для объединения первого и последнего элементов массива inputArray[0] + inputArray[inputArray.length-1]



function addFirstToLast(inputArray) {
  let firstAndLast = ""
   
  // Only execute this code if the array has items in it
  if (inputArray.length > 0) {
    // Change the line below! What should it be?
    let first = inputArray[0]
    let last = inputArray.length === 1 ? "" : inputArray[inputArray.length - 1]
    firstAndLast = first + last;
  }

  return firstAndLast;
}

// The lines of code below will test your function when you run it from the
// command line with Node.js
console.log(addFirstToLast(['first', 'second', 'third']));
console.log(addFirstToLast(['golden', 'terrier']));
console.log(addFirstToLast(['cheerio']));
console.log(addFirstToLast([]));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...