简体   繁体   English

Javascript 字符串字面量语法规则

[英]Javascript string literal syntax rules

Could somebody please explain why有人可以解释为什么

const btn1 = document.querySelector('input[id="btn"]')

requires me to use ('input[id="btn"]') and not ("input[id="btn"]") or ('input[id='btn']') .要求我使用('input[id="btn"]')而不是("input[id="btn"]")('input[id='btn']')

Because the JavaScript engine needs to be able to unambiguously determine where a string literal begins and ends.因为 JavaScript 引擎需要能够明确地确定字符串文字的开始和结束位置。

If an unescaped character which is the same as the string delimiter was permitted inside the string, how would the interpreter determine whether the character was there to terminate the string, or if it was to be interpreted as a literal ' (or " ) to be part of the string?如果在字符串中允许使用与字符串分隔符相同的未转义字符,解释器将如何确定该字符是否存在以终止字符串,或者是否将其解释为文字' (或" )字符串的一部分?

Rigorous syntactical rules are required for the unambiguous evaluation of JavaScript source text to be possible. JavaScript 源文本的明确评估需要严格的句法规则才能成为可能。 (But string escaping is pretty trivial, and common to most all programming languages.) Learn it once, for any language, and you'll probably be well suited for understanding how it can work in many other languages. (但字符串 escaping 非常简单,并且对大多数所有编程语言都很常见。)对于任何语言学习一次,您可能会非常适合理解它如何在许多其他语言中工作。 In JS, it's really not that hard compared to many more complicated constructs (like async / await ).在 JS 中,与许多更复杂的构造(如async / await )相比,它真的没有那么难。

You can remove quotes on attribute selector to prevent a stupid formatting rules:您可以删除属性选择器上的引号以防止愚蠢的格式规则:

const btn1 = document.querySelector('input[id=btn]')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM