注意:扩展运算符将字符串转为真正的数组
const str='hello';
console.log(str)//hello
console.log(...str)//h e l l o
console.log([...str])//(5) ["h", "e", "l", "l", "o"]
const uniStr='x\hell\swo\jknn';
console.log([...uniStr]);//(12) ["x", "h", "e", "l", "l", "s", "w", "o", "j", "k", "n", "n"]
console.log([...uniStr].length);//12
//JavaScript 会将四个字节的 Unicode 字符,识别为 2 个字符
console.log('x\uD83D\uDE80y'.length )//4
console.log([...'x\uD83D\uDE80y'] )//(3) ["x", "?", "y"]
console.log([...'x\uD83D\uDE80y'].length )//3
//封装
function uniLen(str){
return [...str].length;
}
uniLen('x\uD83D\uDE80y')//3
console.log(uniLen('x\uD83D\uDE80y'));//3
//如果不用扩展运算符,字符串的reverse操作就不正确。
let str = 'x\uD83D\uDE80y';
str.split('').reverse().join('')
// 'y\uDE80\uD83Dx'
[...str].reverse().join('')
// 'y\uD83D\uDE80x'