简体   繁体   English

变量已经定义

[英]variable is already defined

sometime i need to replace a variable value to another 有时我需要将变量值替换为另一个

so i use this method 所以我用这种方法

var $$test = "First",
    $$test = "Second";

the code work fine but i use jsfiddle JSHint button to check any error on JavaScript (it helped me a lot) 代码工作正常,但我使用jsfiddle JSHint按钮检查JavaScript上的任何错误(对我有很大帮助)

but i got this error '$$test' is already defined 但是我得到了这个错误'$$ test'已经定义

在此处输入图片说明

so what is the ideal method to re define any variable 那么重新定义任何变量的理想方法是什么

Thank you :) 谢谢 :)

You're getting that error because you're declaring the same variable twice. 之所以收到该错误,是因为您两次声明了相同的变量。

var a = foo, a = bar;

Is the same as: 是相同的:

var a = foo;
var a = bar;

Just break your code in two lines, and you won't get that warning. 只需将代码分成两行,就不会收到警告。 Like this: 像这样:

var a = foo;
a = bar;

Also notice that if you declare a variable with a value, and then right after that you change its value, the first line is a noop . 还要注意,如果声明一个带有值的变量,然后立即更改其值,则第一行是noop

Don't use a comma. 不要使用逗号。 You should redefine it as a new statement: 您应该将其重新定义为新语句:

var $$test = 'First';
$$test = 'Second';

this code is trying to define two variable s called $$test. 这段代码试图定义两个名为$$ test的变量。 They need to have uniuque names. 他们需要有独特的名字。 Try using $$test1 and $$test2 尝试使用$$ test1和$$ test2

updated for you http://jsfiddle.net/9CdJN/2/ 为您更新了http://jsfiddle.net/9CdJN/2/

(function($){

var $$test = "First";
 $$test = "Second";

console.log($$test);

})(jQuery);

The problem is that you have a comma , at the end of the first line instead of a semi-colon ; 问题是您在第一行的末尾有一个逗号,而不是分号; .

Each Javascript statement ends with a semi-colon. 每个Javascript语句均以分号结尾。 You can define multiple variables with a single var by separating them all with a comma. 您可以使用单个var定义多个变量,方法是用逗号将所有变量分开。

var var1=1, var2=2, var3=3;

is the same as 是相同的

var var1=1,
    var2=2,
    var3=3;

Because you had a comma in the first line, the browser believes you are declaring two different variables with the same name. 由于第一行中有逗号,因此浏览器认为您正在声明两个具有相同名称的不同变量。 To fix it, just change it to this: 要修复它,只需将其更改为:

var $$test = "First";
    $$test = "Second";

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

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