简体   繁体   中英

Why isn't the C++ syntax for a string loop used in javascript?

EDIT: I originally thought the following syntax did not work because of a typo in my code and the fact that I have not seen it used in Javascript. I am mainly interested in why I don't see this syntax.

I see strings being looped through like so in C++:

char s[] = "char";                                                                                                                            
for(int i = 0; s[i]; ++i) {
  printf("it is a %c\n", s[i]); 
} 

Why isn't the same syntax, (except just defining the string as s = 'string'; used in Javascript?

ie

  s = "char";                                                                                                                                                                                      
  for(var i = 0; s[i]; i++){
   console.log("it is a " + s[i]);
}

Is this just a matter of convention?

To loop in string, use "length" property.

var s = "char";                                                                                                                                                                                      
  for(var i = 0; i < s.length; i++){
   console.log("it is a " + s[i]);
}

EDIT: To check with your initial condition ...

var s = "char";                                                                                                                                                                                      
  for(var i = 0; s[i] != undefined; i++){
    console.log("it is a " + s[i]);
    }

Try this:

var s="char";
for(var i = 0; s[i]; i++){
   alert("it is a "+s[i]);
}

Working Demo .

It doesnt return undefined. Im getting output as:

    it is a s[i]
    it is a s[i]
    it is a s[i] 
    it is a s[i]

That's because s[i] is being treated as characters rather than the i-th element of the s array.

Instead use line 3 as:

    console.log("it is a " + s[i]);

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