在JavaScript中,字符串是不可变的,而且一旦创建就不能更改它们的内容。不过,有些时候我们需要遍历字符串并访问每个字符的Unicode码点。这时候就用到了String.prototype.charCodeAt方法。
一、codePointAt()方法的介绍
String.prototype.charCodeAt方法返回一个在指定位置的字符的Unicode值。Unicode码点指的是每个字符具有独特的数字,代表Unicode中的特定字符。在ES6引入codePointAt方法之前,charCodeAt方法只返回低16位的值, 所以不能完全表示UTF-16编码的所有字符。
这就是ES6中引入codePointAt方法的原因,它可以返回完整的Unicode码点,具有更好的字符支持和互操作性。
let str = 'Hello World!'; console.log(str.charCodeAt(0)); // 72 console.log(str.charCodeAt(1)); // 101 console.log(str.charCodeAt(6)); // 32
charCodeAt方法还可以接受第二个可选参数,指定从哪个位置开始查找字符的Unicode码点,默认值为0。例如:
let str = 'Hello World!'; console.log(str.charCodeAt(0)); // 72 console.log(str.charCodeAt(1, 2)); // 101 console.log(str.charCodeAt(6)); // 32
二、codePointAt()方法的使用示例
除了返回单个字符的Unicode码点,codePointAt方法还可以返回完整字符的Unicode码点。
let str = '?是一只狗'; console.log(str.charCodeAt(0)); // 55361 console.log(str.charCodeAt(1)); // 57213 console.log(str.charCodeAt(2)); // 26102 console.log(str.charCodeAt(3)); // 32 console.log(str.charCodeAt(4)); // 34892 console.log(str.charCodeAt(5)); // 19968 console.log(str.charCodeAt(6)); // 22303
在上述示例中,我们可以看到,只有使用codePointAt方法才能正确地解析高代理项和低代理项,使得我们可以访问整个字符序列,而不仅仅是每个单独字符的低16位。
三、codePointAt()方法的使用注意事项
需要注意的是,codePointAt方法只适用于Unicode编码字符,对于ASCII字符没有任何影响。如果在一个ASCII字符串中应用了codePointAt方法,它将返回与charCodeAt的结果相同。
另外,如果我们传递一个负的index,codePointAt方法将返回undefined。如果传递的index大于或等于字符串的长度,也会返回undefined。
let str = 'Hello World!'; console.log(str.charCodeAt(-1)); // undefined console.log(str.charCodeAt(99)); // undefined
四、codePointAt()方法的兼容性
codePointAt方法在ES6中引入,因此在旧版本的JavaScript引擎中不可用。我们可以使用polyfill或特性检测来解决这个问题,例如:
if (!String.prototype.codePointAt) { String.prototype.codePointAt = function(pos) { pos = isNaN(pos) ? 0 : pos; var str = this.toString(), code = str.charCodeAt(pos), next = str.charCodeAt(pos + 1), hi, low; if (code >= 0xd800 && code = 0xdc00 && next <= 0xdfff) { hi = code - 0xd800; low = next - 0xdc00; return (hi << 10) + low + 0x10000; } else { return code; } }; }
这个polyfill通过检查每个字符的Unicode码点来模拟codePointAt方法的行为,并正确解析高代理项和低代理项。
五、总结
String.prototype.charCodeAt方法与String.prototype.codePointAt方法用于访问字符串中字符的Unicode码点。然而,在ES6之前,charCodeAt方法不能完全表示UTF-16编码的所有字符的Unicode码点,而codePointAt方法可以返回完整的Unicode码点序列。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/187128.html