简体   繁体   English

在JavaScript中创建和为动态全局变量赋值

[英]creating & Assigning values to dynamic global variables in JavaScript

I have a requirement in my JavaScript code where I update a global variables dynamically to take a particular action based on the value of those variables. 我的JavaScript代码中有一个要求,我会动态更新全局变量,以根据这些变量的值采取特定操作。

Eg : 例如:

this.decEnabled + this.properties.itemIndex = false;  

Here, "this.properties.itemIndex" is integer that helps to distinguish between the items & this.decEnabled is a global variable i am trying to create. 这里,“this.properties.itemIndex”是整数,有助于区分项和this.decEnabled是我想要创建的全局变量。 But I get an error : Uncaught exception: ReferenceError: Cannot assign to 'this.incEnabled + this.properties.itemIndex'. 但是我收到一个错误:未捕获的异常:ReferenceError:无法分配给'this.incEnabled + this.properties.itemIndex'。

I think I am trying to do something which I should not do. 我想我正在尝试做一些我不应该做的事情。 I am wondering whats oing wrong. 我想知道什么是错的。 I tried to assign a string value too as above variable is a string. 我试图分配一个字符串值,因为上面的变量是一个字符串。 Still the same error. 还是一样的错误。 Please suggest. 请建议。

Thanks, 谢谢,
Sneha 斯纳

There are two things in what you have written that do not seem right at all. 你写的东西有两件事似乎不对。

  1. JavaScript Assignment Operator (=). JavaScript赋值运算符(=)。

    This operator works by doing: 该运算符的工作原理如下:

    a) Evaluates the expression from the right side of the '=' sign. a)从'='符号的右侧评估表达式。
    b) Assigns the result to the left hand side expression. b)将结果分配给左侧表达式。

    The problem in your example is (b), the expression on the left is not assignable because you are performing a sum (expressions which involve arithmetic operations are not assignable). 您的示例中的问题是(b),左侧的表达式不可分配,因为您正在执行求和(涉及算术运算的表达式不可分配)。

  2. Global variable : this.decEnabled 全局变量:this.decEnabled

    A global variable is a variable whose scope is the global scope, ie anyone can access that variable. 全局变量是一个变量,其范围是全局范围,即任何人都可以访问该变量。 You can define global variables in the global scope of the document by writing on the top of the document (or outside the scope of any function) the following: 您可以通过在文档的顶部(或任何函数的范围之外)写入以下内容来在文档的全局范围中定义全局变量:

     var global_var; 

    In your explanation you say that you are trying to create the global variable 'this.decEnabled'. 在你的解释中,你说你正在尝试创建全局变量'this.decEnabled'。 However, this cannot be a global variable in any case because you are binding 'decEnabled' to a scope (in this case, you are referring to the current scope by using the 'this' operator). 但是,这在任何情况下都不能是全局变量,因为您将'decEnabled'绑定到范围(在这种情况下,您通过使用'this'运算符来引用当前范围)。

The error that you are receiving is from (1). 您收到的错误来自(1)。

If you are trying to compare values the equality operator that you are looking for is '==' or '==='. 如果您尝试比较值,您要查找的相等运算符是'=='或'==='。

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

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