简体   繁体   中英

Can someone explain this to me simply?

I have been trying to wrap my head around this. I came upon this challenge and don't understand what's going on. On top of that, in the for loop there is an X declared - so you can declare two variables in the for loop parentheses?

There was no var before the x - so that means it's a global variable correct? This is where I'm lost:

str[i] = str[i][0].toUpperCase() + str[i].substr(1);

how does this output the whole string with first letter caps - at the end, str[i].substr(1) should be the second letter, no? JavaScript is zero-indexed

Challenge here: https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-50.php

function capital_letter(str) 
{

    str = str.split(" ");

    for (var i = 0, x = str.length; i < x; i++) {

        str[i] = str[i][0].toUpperCase() + str[i].substr(1);
    }

    return str.join(" ");
}

console.log(capital_letter("Write a JavaScript program to capitalize the first letter of each word of a given string."));

Line by line analysis of the code:

str = str.split(" "); // This line splits the given string str on every space character and saves it in array format

For loop expression analysis:

  • var i = 0, x = str.length // variable 'i' is initialized to 0 and 'x' to length of string array str ie 16

  • i < x; i++ // condition determines whether 'i' on each iteration is smaller than 'x' meaning the loop will run 16 times as the 'i' is incremented by 1

Analysing the line - str[i] = str[i][0].toUpperCase() + str[i].substr(1);

  • str[i][0].toUpperCase() // Make capital the first letter of each str index

  • str[i].substr(1) // take up all letters after only first letter of each str index

At the end the whole word is saved again at the same index

return str.join(" "); // returns the then str array after joining it in to the capitalized sentence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM