本文介绍了确定单词是否为保留的Javascript标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中是否可以确定某个字符串是否是诸如switchiffunction等的保留语言关键字?我想做的是以一种不会破坏特定于浏览器的扩展名的方式来转义动态生成的代码中的保留标识符.我唯一想到的是在try-catch块中使用eval并检查语法错误.虽然不知道如何做到这一点.有什么想法吗?

Is it possible in Javascript to determine if a certain string is a reserved language keyword such as switch, if, function, etc.?What I would like to do is escaping reserved identifiers in dynamically generated code in a way that doesn't break on browser-specific extensions.The only thought coming to my mind is using eval in a try-catch block and check for a syntax error. Not sure how to do that though. Any ideas?

推荐答案

一个方法是:

var reservedWord = false;
try {
  eval('var ' + wordToCheck + ' = 1');
} catch {
  reservedWord = true;
}

唯一的问题是,这将为无效变量名而不是保留字的单词提供假肯定.

The only issue will be that this will give false positive for words that are invalid variable names but not reserved words.

正如评论中指出的那样,这可能是安全隐患.

As pointed out in the comments, this could be a security risk.

这篇关于确定单词是否为保留的Javascript标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 16:17