如果浏览器不支持ES6模板文字,则创建错误消息 [英] creating an error message if browser does not support ES6 Template Literals

查看:117
本文介绍了如果浏览器不支持ES6模板文字,则创建错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在JavaScript中使用字符串文字.如果不支持字符串文字,我希望显示一条错误消息. caniuse

I have been using string literals in my javascript. I would like an error message to be shown if string literals are not supported. caniuse

我的想法是,我将创建一个函数来查看浏览器是否正确解析字符串插值字符串

My Idea was that i would create a function to see if the browser would correctly parse a string interpolated string

    var supportsStringInterpulation = false;
try {
    var stringInsert = 'is a';
    var stringTestExpected = "this " + stringInsert + " test";
    var stringTestAccual = `this ${stringInsert} test`;
    supportsStringInterpolation  = stringTestAccual === stringTestExpected;
}
catch (err) { console.error("failed to render ` ")}

如果正确的话什么都不做

如果错误,则浏览器不支持,然后创建并给出错误消息.

if wrong then the browser does not support then create and give error message.

现在的问题是,当我在IE 11中调试时,我的预期行为是它将失败测试并将supportsStringInterpulation = false进一步发送到我的代码,但它似乎中断并停止了对该脚本的处理.

My problem now is when I debug in IE 11 my expected behavior is that it would fail test and send supportsStringInterpulation = false further down to my code but it appears to break and stop processing that script.

问题1

是否可以将bool值返回到以下问题:当前浏览器是否支持 ES6模板文字?

Is there a way to return a bool value to the question "Does the current Browser support ES6 Template Literals ?

推荐答案

是.这是eval的合法用途之一:

Yes. This is one of the legitimate uses of eval:

var supportsTemplateLiterals = false;
try {
    eval("`foo`");
    supportsTemplateLiterals = true;
}
catch (e) {
}
console.log("Supports template literals? " + supportsTemplateLiterals);

之所以能够工作,是因为主要代码是在ES2015之前的JavaScript引擎上解析的,但是eval 中的代码却没有;解析模板文字上的扼流圈.

It works because the main code parses on a pre-ES2015 JavaScript engine, but the code in the eval doesn't; parsing chokes on the template literal.

在Chrome,Firefox,Edge等设备上显示

On Chrome, Firefox, Edge, etc, that shows


Supports template literals? true

在IE(任何版本)上,它显示:

On IE (any version), it shows:


Supports template literals? false

这篇关于如果浏览器不支持ES6模板文字,则创建错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆