ES6 提供了二进制和八进制数值的新的写法,分别用前缀0b(或0B)和0o(或0O)表示。
(() => {
const { log } = console;
log(0b111110111 === 503); // true
log(0o767 === 503); // true
})()
从 ES5 开始,在严格模式之中,八进制就不再允许使用前缀0表示,ES6 进一步明确,要使用前缀0o表示。
(() => {
// 非严格模式
const { log } = console;
log(0o11 === 011); // true
})();
(() => {
// 严格模式
'use strict';
const { log } = console;
log(0o11 === 011); // Uncaught SyntaxError: Octal literals are not allowed in strict mode.
})();
如果要将0b和0o前缀的字符串数值转为十进制,要使用Number方法。
(() => {
// 严格模式
'use strict';
const { log } = console;
const octalStr = '0b111';
const hexStr = '0o10';
log(Number(octalStr)); // 7
log(parseInt(octalStr, 10)); // 0
log(Number(hexStr)); // 8
log(parseInt(hexStr, 10)); // 0
})();