Determine if a word is a reserved Javascript identifier

笑着哭i 提交于 2019-12-13 00:53:26

问题


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?


回答1:


One option would be to do:

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.




回答2:


I guess you could solve it using eval, but that seems like sort of a hack. I would go for just checking against all reserved words. Something like this:

var reservedWords = [
    'break',
    'case',
    ...
];

function isReservedWord(str) {
    return !!~reservedWords.indexOf(str);
}

Here is a list of all reserved words: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Reserved_Words

Also, a problem with the eval-approach is that some browsers sometimes allows you to use some reserved words as identifiers.



来源:https://stackoverflow.com/questions/16157613/determine-if-a-word-is-a-reserved-javascript-identifier

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!