jac*_*cky 11 javascript google-chrome ecmascript-5
我想看看我在浏览器中使用的ECMAscript版本(例如,chrome 59),因为在处理RegExp的东西时,ECMAscript3和ECMAscript5之间存在一些差异.
我已经找到了相关的相关信息,但我找不到有关如何检测ECMAscript版本的具体答案.
提前致谢.
可能是你可以尝试使用在特意增加了一些数据结构ES6一样Map,Set等等,这是区分ES5和ES6,但你可以看一下对于在附加功能ES5中不存在在ES3你的情况?
try {
var k = new Map();
console.log("ES6 supported!!")
} catch(err) {
console.log("ES6 not supported :(")
}
try {
var k = new HashMap();
console.log("ES100 supported!!")
} catch(err) {
console.log("ES100 not supported :(")
}Run Code Online (Sandbox Code Playgroud)
ECMAScript 是一个行业标准:
ECMAScript 是 Ecma International 在 ECMA-262 和 ISO/IEC 16262 中标准化的商标脚本语言规范。它的创建是为了标准化 JavaScript,以促进多种独立的实现。
Javascript 或多或少是一种流行的实现:
自标准首次发布以来,JavaScript 一直是 ECMAScript 最著名的实现,其他知名的实现包括 JScript 和 ActionScript。维基百科
考虑到各种浏览器、node.js 等中 JavaScript 实现的当前状态,没有人专门对自己进行版本控制,而是不断发展新功能。因此,最好的方法是检测(可能使用第 3 方库)所需的功能是否存在,然后使用。否则就退回到更传统的一种。通常是尝试一些操作,然后检查是否符合预期,没有什么神奇的。
这是一个扩展的 ECMAScript 检测器(基于 @Infigon 的答案)。
var ecmaScriptInfo = (function() {
// () => { is not allowed
function getESEdition() {
var array = [];
switch (true) {
case !Array.isArray:
return 3;
case !window.Promise:
return 5;
case !array.includes:
return 6;
case !''.padStart:
return 7;
case !Promise.prototype.finally:
return 8;
case !window.BigInt:
return 9;
case !Promise.allSettled:
return 10;
case !''.replaceAll:
return 11;
case !array.at:
return 12;
default:
return 13;
}
}
function getESYear(edition) {
return {
3: 1999,
5: 2009
}[edition] || (2009 + edition); // nullish coalescing (??) is not allowed
}
var edition = getESEdition();
var year = getESYear(edition);
return {
edition: edition, // usually shortened [edition,]
year: year, // usually shortened [year,]
text: 'Edition: '+ edition +' | Year: '+ year
// `Edition: ${edition} | Year: ${year}` is not allowed
}
})();
console.log(ecmaScriptInfo.edition);
console.log(ecmaScriptInfo.year);
console.log(ecmaScriptInfo.text);Run Code Online (Sandbox Code Playgroud)
新增和变更内容为:
console.log(ecmaScriptInfo.edition)。笔记:
箭头函数表达式在第 10 版(2019 年)中引入;这就是为什么使用标准函数调用的原因。
Nullish Coalescing在第 11 版(2020 年)中引入;因此,为什么使用逻辑 OR (||)(逻辑或)。
对象字面量共享键和值简写出现在后来的版本中;因此为什么
edition: edition没有缩短。模板文字在第 9 版(2018 年)中引入;因此为什么
Edition: ${edition} | Year: ${year}没有使用。
var被使用而不是const因为常量可能会超出旧浏览器中的块范围[来源]
| 归档时间: |
|
| 查看次数: |
7376 次 |
| 最近记录: |