codePointAt() 方法返回 一个 Unicode 编码点值的非负整数。
语法
str.codePointAt(pos)参数
-  
         pos
- 这个字符串中需要转码的元素的位置。
返回值
返回值是在字符串中的给定索引的编码单元体现的数字,如果在索引处没找到元素则返回 undefined 。
描述
如果在指定的位置没有元素则返回 undefined 。如果在索引处开始没有UTF-16 代理对,将直接返回在那个索引处的编码单元。
Surrogate Pair是UTF-16中用于扩展字符而使用的编码方式,是一种采用四个字节(两个UTF-16编码)来表示一个字符,称作代理对。
例子
使用 codePointAt()
 
       'ABC'.codePointAt(1); // 66 '\uD800\uDC00'.codePointAt(0); // 65536 'XYZ'.codePointAt(42); // undefined
替补支持(Polyfill)
给原生不支持 ECMAScript 6 的浏览器使用codePointAt()方法的的一个字符串扩展方法。
/*! http://mths.be/codepointat v0.1.0 by @mathias */
if (!String.prototype.codePointAt) {
  (function() {
    'use strict'; // 严格模式,needed to support `apply`/`call` with `undefined`/`null`
    var codePointAt = function(position) {
      if (this == null) {
        throw TypeError();
      }
      var string = String(this);
      var size = string.length;
      // 变成整数
      var index = position ? Number(position) : 0;
      if (index != index) { // better `isNaN`
        index = 0;
      }
      // 边界
      if (index < 0 || index >= size) {
        return undefined;
      }
      // 第一个编码单元
      var first = string.charCodeAt(index);
      var second;
      if ( // 检查是否开始 surrogate pair
        first >= 0xD800 && first <= 0xDBFF && // high surrogate
        size > index + 1 // 下一个编码单元
      ) {
        second = string.charCodeAt(index + 1);
        if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
          // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
          return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
        }
      }
      return first;
    };
    if (Object.defineProperty) {
      Object.defineProperty(String.prototype, 'codePointAt', {
        'value': codePointAt,
        'configurable': true,
        'writable': true
      });
    } else {
      String.prototype.codePointAt = codePointAt;
    }
  }());
}
 
       规范
| Specification | Status | Comment | 
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) String.prototype.codePointAt | Standard | Initial definition. | 
| ECMAScript Latest Draft (ECMA-262) String.prototype.codePointAt | Draft | 
浏览器兼容性
 
         We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. 
         Find out how you can help! 
        
 
         
       | 特性 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari | 
|---|---|---|---|---|---|
| 基本支持 | 41 | 29 (29) | 11 | 28 | 未实现 | 
| 特性 | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | 
|---|---|---|---|---|---|---|
| 基本支持 | 未实现 | 未实现 | 29.0 (29) | 未实现 | 未实现 | 未实现 |