Javascript变量名命名规则

本文详细介绍了JavaScript中变量命名的有效规则,包括不能以数字开头、避免使用特殊符号和保留关键字等。此外,还提供了如何有效避免常见陷阱的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文链接
测试命名是否有效的在线工具

The following are the rules for naming JavaScript variables:

  1. A variable name cannot start with a numeral. For instance, 3x or 2goats or 76trombones would all be illegal variable names.You can, however, have numbers within a JavaScript variable name; for instance up2me or go4it would both be perfectly valid variable names.

  2. You cannot have a mathematical or logical operator in a variable name. For instance, 2*something or this+that would both be illegal… because the * and the + are arithmetic operators. The same holds true for ^, /, , !, etc.

  3. You must not use any punctuation marks of any kind in a JavaScript variable name, other than the underscore; for example… some:thing or big# or do’to would all be illegal.
    The underscore is the exception, and it can be used at the beginning, within, or at the end of JavaScript variable names. You can use names like pounds or some_thing or gallons as variable names and they are perfectly legal.
    (但是变量名尽量不要以下划线开头—— 以下划线开头的被某些JavaScript设计为特殊的含义,因此可能让人迷惑。)

  4. JavaScript names must not contain spaces. Ever.

  5. You cannot use JavaScript keywords (parts of the language, itself) for variable names. Thus window or open or location or string would be illegal. Check a JavaScript reference if in doubt as to whether something is or is not part of the language – JavaScript has grown into a fairly fully-fleshed language, so you may get some occasional surprises.
    You can, of course, use what are otherwise keywords as parts of variable names. For instance, thatWindow or someString or theLocation would all be perfectly acceptable.

  6. JavaScript variable names are case-sensitive. Programmers in other languages are often tripped up by this one, as some languages are not sensitive to case in variable names.For instance, all of the following names would be considered completely different variable names in JavaScript: gasbag Gasbag GasBag gasBa

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值