简体   繁体   English

检查是否全部在下的功能

[英]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 : 我正被介绍给Java语言,我有一个基本的函数可以编写:它应该检查字符串中的每个字母是否都较低并且根据返回true或false进行了尝试,但我尝试编写它,但是返回“ undefined” “而不是true / false,我不明白为什么,这是代码:

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 . 代码的问题是,您正在尝试访问window scope charAt函数。 But actually it is available in the prototype of a string , 但实际上它可以在stringprototype中使用,

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 : 我尝试编写它,但是它返回“ undefined”而不是true / false,我不明白为什么,这是代码:

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. charAt不是全局方法,它是字符串方法。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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