admin管理员组

文章数量:1384106

new javascript student here looking for a little clarification. I keep running into problems involving For Loops/Arrays. I'm not familiar enough with the concepts to diagnose my own problems. The online mini course I'm starting out with has limited examples and includes more plex problems on the exercises (which I think is great! I don't mind digging for answers). I try to google for help but can't seem to find anything that explains what I'm doing wrong. I'd really appreciate it if someone could take a look below and shed some light on where and why I'm making mistakes.

Here is the exercise with the instructions mented just below:

function wordsToSentence(words) {

// words is an array of strings // return a string that is all of the words concatenated together // spaces need to be between each word // example: ['Hello', 'world!'] -> 'Hello world!' }

And here is my code that I put in to satisfy the test (which keeps failing):

function wordsToSentence(words) {
for (var i = 0; i < words.length; i++) {
    words[i] + ' ';

}
    return words;
}

More than someone just giving me the correct code, I'd really really appreciate it if someone could break down what I did wrong and how to do it right. Thanks in advance!

new javascript student here looking for a little clarification. I keep running into problems involving For Loops/Arrays. I'm not familiar enough with the concepts to diagnose my own problems. The online mini course I'm starting out with has limited examples and includes more plex problems on the exercises (which I think is great! I don't mind digging for answers). I try to google for help but can't seem to find anything that explains what I'm doing wrong. I'd really appreciate it if someone could take a look below and shed some light on where and why I'm making mistakes.

Here is the exercise with the instructions mented just below:

function wordsToSentence(words) {

// words is an array of strings // return a string that is all of the words concatenated together // spaces need to be between each word // example: ['Hello', 'world!'] -> 'Hello world!' }

And here is my code that I put in to satisfy the test (which keeps failing):

function wordsToSentence(words) {
for (var i = 0; i < words.length; i++) {
    words[i] + ' ';

}
    return words;
}

More than someone just giving me the correct code, I'd really really appreciate it if someone could break down what I did wrong and how to do it right. Thanks in advance!

Share Improve this question asked Aug 17, 2017 at 20:38 SwanziSwanzi 331 silver badge5 bronze badges 1
  • 1 words.join(" "); – ASDFGerte Commented Aug 17, 2017 at 20:39
Add a ment  | 

5 Answers 5

Reset to default 3

you are not actually adding words. First declare an empty string in a variable. This will be your base string, now as you loop over the array keep appending a space and a word to this string. Then return the string and not array. you can use trim() at the end to remove any extra spaces in the end or beginning before returning the string.

function wordsToSentence(words) {
   var sentence = ""; //empty string
   for (var i = 0; i < words.length; i++) {
      sentence += ' ' + words[i]; //add space and word to string
   }
   return sentence.trim(); //return the string formed
}

console.log(wordsToSentence(['this', 'is', 'a', 'sentence']));

function wordsToSentence(words) {
  for (var i = 0; i < words.length; i++) {
    words[i] + ' ';

  }
  return words;
}

This is your code. What you are doing here is going through the array and adding a white space to every word, not even assigning it. Then returning the array. The best solution is (as in the ments):

  function wordsToSentence(words) {
    return words.join(' ');
  }

https://developer.mozilla/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/join

words = ["test", "hello", "world"]


function wordsToSentence(words) {
var stringResult = ""; //create an empty string
for (var i = 0; i < words.length; i++) {
    stringResult += words[i] + " "; //concatenate using +=, retrieving the value using words[i] and append with a space in the end.

}
    return stringResult.trim(); //return the string, with the trim function that strips the last space of it.
}

console.log(wordsToSentence(words));

There are a lot of other options to solve this too:

Using join --> join glues the array parts together using a string value.

words = ["test", "hello", "world"]


console.log(words.join(", "));

Using reduce --> method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value (source MDN). Basically it uses a condition to flatten all the values into a single value. In this case a string.

words = ["test", "hello", "world"]


console.log(words.reduce(function(a, b){
  return a.concat(" ", b);
}));

Nowadays Array.prototype.forEach is monly available in most browsers (since IE9). This eliminates the use for bulky for loops:

words.forEach(function(element){
    ...
     //iterates over every entry in the array. Made available by the argument element. 
});

In emcascript 6 this can be even shorter by using arrow functions:

words.forEach( (element) => {...} );

Read more about array and all the array methods at https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Well.. You have to get functional a bit;

var arr = ['Hello', 'world!']
    res = arr.reduce((p,c) => p + " " + c);
console.log(res);

The .reduce() function here which does not take an initial value, works like applying the provided callback function among the first two adjacent items of the subject list (arr here) and storing the result back in p which happens to be the next first item and proceeds up until the end of the list. p stands for "previous" and c for current.

Maybe this could help you:

function wordsToSentence(words) {
    var words = ['Hello', 'there', 'Javascript!', 'yeah!'];
    var concatenated = '';  

    for (var i = 0; i < words.length; i++) {
        concatenated += words[i] + ' ';
    }

    concatenated = concatenated.slice(0, -1);

    return concatenated;

}

本文标签: javascriptReturn a string that is all of the words concatenated togetherStack Overflow