简体   繁体   English

jQuery更多变量分号或逗号-基本

[英]jQuery more variables semicolon or comma - basic

I know we can just use one var for many variables and use comma to separate them 我知道我们可以只使用一个var对很多变量和使用逗号将它们分开

var text1 = 'abc',
    text2 = 'bcd',
    text3 = 'dfg'

but if my variables are 但是如果我的变量是

var text1 = 'abc',
    text2 = 'bcd',
    text3 = 'dfg',
    text4 = $(this).find('div').next('li');
    text5 = $(this).find('div2').next('li2');

I found comma at the end of text4 is not correct, if the case like that do we still need comma to separate or semicolon with a var in the front? 我发现text4末尾的逗号不正确,如果是那样的情况,我们是否仍需要逗号分隔或分号,并在前面加上var

var var1 = val1,
    var2 = val2;

is equivalent to: 等效于:

var var1 = val1;
var var2 = val2;

Commas are for separating multiple variable declarations within one var statement, semicolons are for separating multiple statements. 逗号用于在一个var语句中分隔多个变量声明,分号用于分隔多个语句。 So when you use semicolon, you have to use the var keyword again because you're starting a new statement. 因此,当使用分号时,因为要开始新的语句,所以必须再次使用var关键字。

If you use a semicolon and don't use the var keyword in the new statement, you'll be assigning a global variable, not declaring a local one. 如果您使用分号而不在new语句中使用var关键字,则将分配一个全局变量,而不是声明一个局部变量。

Here's a visual answer; 这是一个视觉答案; JavaScript interprets your code like this: JavaScript会这样解释您的代码:

var text1 = 'abc',
    text2 = 'bcd',
    text3 = 'dfg',
    text4 = $(this).find('div').next('li');

text5 = $(this).find('div2').next('li2');

This is a great example of a semantic error, meaning that your code is syntactically correct but does not do what you meant. 这是语义错误的一个很好的例子,这意味着您的代码在语法上是正确的,但没有按照您的意思执行。 Importantly, JavaScript will make text5 a global variable because it was declared without var . 重要的是,JavaScript将使text5成为全局变量,因为它是在没有var情况下声明的。

See these two SO questions for more information: 有关更多信息,请参见以下两个SO问题:

  1. What is the purpose of the var keyword and when to use it (or omit it)? var关键字的目的是什么?何时使用(或省略)?
  2. Declaring Multiple Variables in JavaScript 在JavaScript中声明多个变量

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

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