如果第二个参数 bUnicode255For1 === true,则所有字符长度为 1
否则如果字符 Unicode 编码 > 255 则长度为 2
function strLength(s, bUnicode255For1) { if(bUnicode255For1 === true){ return s.length; } var num = 0;; //es6 ( for of ) //for(var x of s){ // x.charCodeAt()>255?num+=2:num+=1; //} for(var i=0;i<s.length;i++){ s.charCodeAt(i)>255?num+=2:num+=1; } return num; }
用es6 新特性 for of 更加简单 可是牛客不支持~~