Maison  >  Questions et réponses  >  le corps du texte

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 *&^');
高洛峰高洛峰2730 Il y a quelques jours774

répondre à tous(3)je répondrai

  • 伊谢尔伦

    伊谢尔伦2017-04-10 17:13:11

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

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

    répondre
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-10 17:13:11

    我帮你想一种另外的方式

    function func(string){
        var str,
            word=0,
            num=0,
            space=0,
            other=0;
            
        str = string.replace(/[a-zA-Z]/g,'');
        word = string.length - str.length;
            
        string = str;
            
        str = string.replace(/\d/g,'');
        num= string.length - str.length;
            
        string = str;
            
        str = string.replace(/ /g,'');
        space= string.length - str.length;
            
        other= str.length;
            
        console.log(word,num,space,other);
    }
    
    func('12qw *&^');

    répondre
    0
  • 大家讲道理

    大家讲道理2017-04-10 17:13:11

    首先要了解不同类型变量比较的规则:

    1. 如果两个操作数都是数值,则执行数值比较。

    2. 如果两个操作数都是字符串,则比较两个字符串对应的字符编码值。即ASCII码值,用charCodeAt方法即可得到

    3. 如果一个操作数是数值,则将另一个操作数转换为一个数值,然后进行数值比较

    4. 如果一个操作数是对象,则调用这个对象的valueOf方法,用按照1,2,3规则进行比较;如果 没有valueOf方法,则调用toString方法,按照1,2,3规则进行比较

    回到这个问题,出错的地方就是有一个空格的单字符串和数字0,9的比较,即第二个判断条件。
    循环开始,
    当i=0;str.charAt(i)='1'时,字符串'1'强制类型转换成数字1,满足条件,num++;
    当i=1;str.charAt(i)='2'时情况同上;
    当i=3;str.charAt(i)=' ',有一个空格字符的单字符串,此时同样强制类型转换为了数字0,满足条件0<=0&&0<==9,num++,num=3;

    此处强制类型转换是利用Number(str)->number。可以在控制台加断点一步一步调试。
    参考:ASCII码,字符串转换为数字

    répondre
    0
  • Annulerrépondre