[英]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
函數。 但實際上它可以在string
的prototype
中使用,
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.