javascript - 判断字符串中个字符的数量有个问题

查看:83
本文介绍了javascript - 判断字符串中个字符的数量有个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

用普通的for+if语句判断字符串中字母,数字,空格,其他字符的数目

function func(string){
var str=string,word=0,num=0,space=0,other=0;
for(var i=0,count=str.length;i<count;i++)
 {if('A'<=str.charAt(i)&&str.charAt(i)<='Z'||'a'<=str.charAt(i)&&str.charAt(i)<='z')
       word++;
  else if(0<=str.charAt(i)&&str.charAt(i)<=9)
     num++;                 
  else if(str.charAt(i)==' ')    
    space++;             
  else
    other++;                
     } 
 document.write('word:'+word+"<br/>");//2
 document.write('number:'+num+"<br/>");//3?为什么这样?
 document.write('space:'+space+"<br/>");//0?为什么?
 document.write('otner char:'+other+"<br/>");//3
}
func('12qw *&^');

解决方案

else if(0<=str.charAt(i)&&str.charAt(i)<=9)
改成
else if('0'<=str.charAt(i)&&str.charAt(i)<='9')

一个是数字0~9,一个是数字字符'0'~'9',两者是不一样的

这篇关于javascript - 判断字符串中个字符的数量有个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆