繁体   English   中英

检查是否全部在下的功能

[英]Function that checks if all in Lower

我正被介绍给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;
}

您可以通过以下方式轻松实现:

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

无需一一遍历并检查字符。

代码的问题是,您正在尝试访问window scope charAt函数。 但实际上它可以在stringprototype中使用,

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

我尝试编写它,但是它返回“ undefined”而不是true / false,我不明白为什么,这是代码:

原因很简单,因为您没有调用该函数;)

其次,您的代码不正确。 charAt不是全局方法,它是字符串方法。

做了

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

你可以试试:

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