ES2018(ES9) 马上发布,新特性包括:异步迭代器、对象展开运算符、Promise.prototype.finally、非转义序列的模板字符串、正则表达式 s/dotAll 模式、等等...
本网站主要用于测试你对 ES2018(ES9) 的掌握情况,答案可在 esnext.justjavac.com 找到,前端交流 QQ 群: 599243863
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; console.log(z);
let { ...obj } = Object.create({ x: 1 }); console.log(obj.x);
function fn1(obj) { let { x, y, ...z } = obj; return { x, y, z }; } function fn2(obj) { let { x, ...n } = obj; let { y, ...z } = n; return { x, y, z }; }
let { x, y, ...z } = null; console.log(z);
TypeError: Cannot destructure property `x` of 'undefined' or 'null'.
运行时错误。
let obj = { x: 1, y: 2, a: 3, b: 4 }; let { ...x, y, z } = obj; console.log(x);
SyntaxError: Rest element must be last element
let obj = { x: 1, y: 2, a: 3, b: 4 }; let objWithXGetter = { ...obj, get x() { throw new Error() } };
let objWithXGetter = {}; Object.assign(objWithXGetter, a); Object.defineProperty(objWithXGetter, "x", { get(){ throw new Error() }, enumerable : true, configurable : true });不会抛出异常。
let obj = { x: 1, y: 2, a: 3, b: 4 }; let objWithXGetter = { ...obj, ...{ get x() { throw new Error() } } };
.x
被调用了,所以抛出了异常
let emptyObject = { ...null, ...undefined }; let emptyArray = [...null, ...undefined];
null
和
undefined
,数组会抛异常 WTF
let x = { a: 1, b: 2 }; let y = [ ...x ];
TypeError: x is not iterable
let x = { a: 1, b: 2, length: 2 }; let y = [ ...x ];
TypeError: x is not iterable
let x = [ 1, 2 ]; let { ...y } = x; console.log(y);
x
被转换成对象。
let x = { a: 1 }; let o = { __proto__: null, b: 2, ...x }; console.log(o);
let o = { __proto__: null }
和
let o = Object.create(null)
一样,都是创建一个真正的空对象,比
let o = {}
,因为这个对象没有原型链。
let x = `\u{55}`; x.length;
\u
开始的为 unicode 转义字符。
let x = `\unicode`; x.length;
SyntaxError: Invalid Unicode escape sequence
非法的 Unicode 转义序列。
let x = String.raw`\u{55}`; x.length;
String.raw
返回字符串的原始表示
let x = String.raw`\unicode`; x.length;
String.raw
的行为,非法的转义序列不再抛出异常
function tag(str) { return str[0].toUpperCase(); } tag`justjavac`;
function tag(str) { return str[0]; } tag`\unicode`;
undefined
let regex = /^.$/; regex.test('道'); regex.test('😀');
charCodeAt()
方法来返回指定索引处字符的 Unicode 数值,但是 Unicode 编码单元 > 0x10000 的除外,ES2015 中又增加了一个新的方法
codePointAt()
可以返回大于 0x10000 字符串的数值。 JavaScript 虽然默认支持 Unicode,但是 JavaScript 的编码方式是 UCS-2,所有字符都是 2 个字节,如果是 4 个字节的字符,会当作两个双字节的字符处理。在
ES6 中,正则表达式的
u
标识启用对 Unicode 特殊字符的支持。因此我们使用
let regex = /^.$/u
可以得到期望的结果
true true
。
let regex = /./; regex.test('\n'); regex.test('\r'); regex.test('\v'); regex.test('\f'); regex.test('\u{2028}'); regex.test('\u{2029}'); regex.test('\u{0085}');
.
可以匹配换行符以外的任意字符,换行符包括
\n
、
\r
、
\u{2028}
、
\u{2029}
。 还有一些其它字符,虽然也可以作为一行的开始,但是
.
可以匹配,包括
\v
、
\f
、
\u{0085}
。 ES2018 为正则表达式增加了 s/dotAll 标志,可以让
.
匹配任意字符,所以
let regex = /./s
可以使以上代码都返回
true
。