如果第二个参数 bUnicode255For1 === true,则所有字符长度为 1
否则如果字符 Unicode 编码 > 255 则长度为 2
function strLength(s, bUnicode255For1) { if (bUnicode255For1) {//仅仅判断是否是true还是false return s.length;//true直接返回长度 } else { for (var i = 0, length = 0; i < s.length; i++) { if (s.charCodeAt(i) > 255) {//判断每一个字符的Unicode编码如果大于255时字符串长度加2 length = length + 2; } else { length++; } } return length; } }
function strLength(s, bUnicode255For1) { if(bUnicode255For1){ return s.length } let arr=s.split("") return arr.reduce((acc,item)=>{ acc +=item.charCodeAt()>255?2:1 return acc },0) }
function strLength(s, bUnicode255For1) { let len = 0 for(let i = 0;i < s.length;i++){ len += s[i].charCodeAt() > 255 && !bUnicode255For1 ? 2 : 1 } return len }
function strLength(s, bUnicode255For1) { let str = s.split('') let num = 0 if(bUnicode255For1 === true){ num = str.length }else{ for(let i=0;i<str.length;i++){ num += s.charCodeAt(i)>255 ? 2 : 1 } } return num }
function strLength(s, bUnicode255For1) { var Len = 0; if(bUnicode255For1){ return s.length; }else{ for(var i = 0;i< s.length;i++){ if(s.charCodeAt(i) > 255){ Len +=2; }else{ Len +=1; } } return Len; } } console.log( strLength('牛客, hello world', false))
function strLength(s, bUnicode255For1) { var num = 0; if (s === '') { return 0; } if (bUnicode255For1) { return s.length; } else { for (let i = 0; i < s.length; i++) { if (s.charCodeAt(i) > 255) { num += 2; } else { num += 1; } } return num; } }