简体   繁体   中英

Why Is My Variable Not Declaring In JavaScript

if we write:
window['anime'] = 'one punch man'

then we can access simply by:
console.log(anime)

but if we do:
window['%'] = 'symbol'

then this gives a syntax error:
console.log(%)

why is this happening?

Give this a quick read through ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types ), it is about JavaScript valid identifiers. Essentially, % is not a valid one, hence the error.

You could do window['percent'] , window['PERCENT'] , window['_PERCENT'] , window['$percent'] , etc. As long as you conform to the rules.

From the website:

You use variables as symbolic names for values in your application. The names of variables, called identifiers, conform to certain rules.

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($). Subsequent characters can also be digits (0–9).

Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) as well as "a" through "z" (lowercase).

You can use most of ISO 8859-1 or Unicode letters such as å and ü in identifiers. (For more details, see this blog post.) You can also use the Unicode escape sequences as characters in identifiers.

Some examples of legal names are Number_hits, temp99, $credit, and _name.

In JavaScript you can't declare a variable name as % since it can contain only letters, digits, underscores and dollar signs (but it can't begin with a digit).

So, when you do window['anime'] = 'one punch man' , a global anime variable will be automatically created.
But, when you do window['%'] = 'symbol' , it won't happen the same for % , since it doesn't follow the aforementioned rules.

% is being used in JS as a remainder operator and for that reason cannot be used as a variable name or to access values.

This article provides more info as to what can or can't be used as a variable name in JS: https://mathiasbynens.be/notes/javascript-identifiers-es6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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