简体   繁体   中英

Function that checks if all in Lower

I'm getting introduced to Javascript language and I have a basic function to write : it's supposed to check if every letter in a string is in lower and returns true or false according to, i've tried to write it but it returns "undefined" instead of true/false and I don't get why, here is the code :

var s="hello";
var toutEnMinuscules = function(s){
  var i=0;
  var x=true;
  for (i; i<s.length; i++ ){
    if(charAt(i)!==charAt(i).toLowerCase()){
      x=false;
      break;
    }
  }
  return x;
}

You can do it simply by,

var s="hello";
var isAllLower = s.toLowerCase() == s;

No need to iterate and check the characters one by one.

The problem with your code is, you are trying to access the function charAt in window scope . But actually it is available in the prototype of a string ,

if(s.charAt(i)!==s.charAt(i).toLowerCase()){
//-^  -----------^

i've tried to write it but it returns "undefined" instead of true/false and I don't get why, here is the code :

Reason is simple, because you are not invoking the function ;)

Secondly, your code is incorrect. charAt is not a global method, it is string method.

Make it

var s="hello";
var toutEnMinuscules = function(s){
  var i=0;
  var x=true;
  for (i; i<s.length; i++ ){
    if(s.charAt(i)!==s.charAt(i).toLowerCase()){ //observe that this line has changed to invoke a string function
      x=false;
      break;
    }
  }
  return x;
}
toutEnMinuscules (s); //this line has been added to invoke the function

you can try:

function isAllLower(str){
    return str.search(/^[a-z\s]*$/g)>-1;
}

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