输入字符串统计查询字符串字节数

刚接触JavaScript,教程里面有一道题目就做了一下,记录一下。题目是输入一段任意字符串计算字符串的字节(提示有一个汉字二个字节,一个英文或字符一个字节。通过 charCodeAt获得Unicode如果大于255是汉字否则是英文或字符。),循环判断是汉字还是别的然后统计了。
function len(str) {
            if (str === '') {
                alert('请输入查询字符');
                return;
            }
            var num = 0;
            for (i = 0; i < str.length; i++) {
                leng = str.charCodeAt(i);
                if (leng > 255) {
                    count = 2;
                } else {
                    count = 1;
                }
                num += count;
            }
            console.log(num);
        }

        len(window.prompt('input'))

你可能感兴趣的:(输入字符串统计查询字符串字节数)