javascript 如何重置变量值(删除 - 未定义 - 空)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24243589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:26:45  来源:igfitidea点击:

How to reset a variables value (delete - undefined - null)

javascriptvariablesundefined

提问by user3742773

I read if you declare a variable you can not delete it.
If you leave it undeclared you can.
I also read if you do not declare a variable it can cause issues later.

我读到如果你声明了一个变量,你就不能删除它。
如果你不申报,你可以。
我还读到如果你不声明一个变量,它可能会在以后引起问题。

Certain lints I have used have pointed out declared and undeclared issues in some of the stuff I have written, to stop the reporting of these issues and based off of all the information I have read thus far, I have opted to declare all my variables.

我使用的某些 lints 指出了我写的一些东西中声明和未声明的问题,以停止报告这些问题,并根据我迄今为止阅读的所有信息,我选择声明我的所有变量。

Now here is where this becomes confusing for me.

现在这让我感到困惑。

I am trying to build a random name generator that utilizes a Math.randomroutine, when I try to recycle this routine it adds to the previous one, I have tried to set the var undefined / null (which in themselves can be variables that are defined) and it still just adds the new results to the old ones, this is making the feature of regenerating a new name if you do not like the old one useless.

我正在尝试构建一个利用Math.random例程的随机名称生成器,当我尝试回收该例程时,它会添加到前一个例程中,我尝试设置 var undefined / null(它们本身可以是已定义的变量)和它仍然只是将新结果添加到旧结果中,这使得如果您不喜欢旧名称则重新生成新名称的功能无用。

After writing this I realized my question is two part:

写完这篇之后,我意识到我的问题有两个部分:

  • How to do you delete a value from a var and restart?
  • Is declaring your variables really that important?
  • 如何从 var 中删除一个值并重新启动?
  • 声明变量真的那么重要吗?

I have yet to find any solid information on the difference between declared and undeclared other than it changes the inherent properties of the variables (mainly if a variable can be deleted or not)

我还没有找到任何关于声明和未声明之间区别的可靠信息,除了它改变了变量的固有属性(主要是变量是否可以删除)

var nameLength = Math.floor(Math.random() * (13 - 3) + 3); /* min 3 max 13*/
testValue = Math.floor(Math.random() * (13 - 3) + 3);
var compareLetter = 0;
var randomLetter = "";
var randomName = "";
var capitolLetter = "";
var checkLetter = 0;
var nameTitle = "XXX"; /* titles add _ between title and name*/
var nameLetters = [
    ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"],
    ["a", "e", "i", "o", "u"],
    ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
];
if (nameTitle !== "") { /* my attempt to subtract title length +1 from name length if over 13*/
    nameLength = nameLength + (nameTitle.length + 1);
    if (nameLength > 13) {
        nameLength = nameLength - (nameLength - 13);
    }
}
for (i = 0; i < nameLength; i++) {
    randomLetter = nameLetters[compareLetter][Math.floor(Math.random() * nameLetters[compareLetter].length)];
    checkLetter = nameLetters[1].indexOf(randomLetter);
    if (checkLetter > -1) { /* my version of keeping consanants and vowels from stacking up */
        compareLetter = 2;
    } else {
        compareLetter = 1;
    }
    if (randomName.length < 1) { /* my version to keep first letter capitolized*/
        capitolLetter = randomLetter.toUpperCase();
        randomName = randomName + capitolLetter;
    } else {
        randomName = randomName + randomLetter;
    }
}
if (nameTitle !== "") {
    alert(nameTitle + "_" + randomName);
} else {
    alert(randomName);
}
alert("this is nameLength" + nameLength);
alert("this is testValue " + testValue);
delete nameLength;
delete testValue;
alert("this is nameLength" + nameLength);
alert("this is testValue " + testValue); /* notice this was not displayed*/
http://jsfiddle.net/OldGuyGamer/PJsZ3/4/

here is what I am working with, keep in mind that fiddle seems to GC after each run, the environment I am setting this up in does not do that.

这是我正在使用的,请记住,每次运行后 fiddle 似乎都在 GC,我设置的环境不会这样做。

回答by basarat

I read if you declare a variable you can not delete it.

我读到如果你声明了一个变量,你就不能删除它。

yes. e.g. var foo = 1; delete foo; console.log(foo); // 1

是的。例如 var foo = 1; 删除 foo; 控制台日志(富);// 1

BUT the thing to take a way is .. do not delete a variable

但是要采取的方法是..不要删除变量

Only delete members. e.g. delete foo.bar

只删除成员。例如delete foo.bar

Instead of deleting a variable you can reinitialize it to an empty state i.e. foo = undefined

您可以将其重新初始化为空状态,而不是删除变量,即 foo = undefined

回答by RobG

How to do you delete a value from a var and restart?

如何从 var 中删除一个值并重新启动?

You can't delete declared global variables because ECMA-262 says they must be intialised as not deletable. You can't delete declared function variables because you can't access the "variable object" that they are attached to.

您不能删除声明的全局变量,因为 ECMA-262 规定它们必须初始化为不可删除。您无法删除声明的函数变量,因为您无法访问它们所附加的“变量对象”。

Is declaring your variables really that important

声明变量真的那么重要吗

Declaring variables constrains their scope to the current execution context. Not declaring a variable means that it becomes a property of the global object when the code assigning it a value is executed. If all variables are global, you start running into problems with name clashes, e.g. every counter in a for loop must be different in every loop in every function.

声明变量将它们的范围限制在当前执行上下文中。不声明变量意味着在执行为其赋值的代码时,它成为全局对象的属性。如果所有变量都是全局变量,您就会遇到名称冲突的问题,例如,for 循环中的每个计数器在每个函数的每个循环中都必须不同。

So if you want "deletable variables", then make them properties of some global object and you can treat them more or less like variables and delete them, e.g.

因此,如果您想要“可删除的变量”,则使它们成为某个全局对象的属性,您可以或多或少地将它们视为变量并删除它们,例如

var u = void 0;
var globalObj = {varOne:u, varTwo:u, varThree:u};

delete globalObj.varOne;

You could do something similar using the global object like:

您可以使用全局对象执行类似的操作,例如:

var globalObj = this;
varOne = varTwo = varThree = void 0;

delete globalObj.varOne;

I think the first approach is preferred, however you haven't provided enough detail to provide any objective analysis of which will suit your case better.

我认为第一种方法是首选,但是您没有提供足够的细节来提供任何更适合您的情况的客观分析。

Edit

编辑

I have yet to find any solid information on the difference between declared and undeclared other than it changes the inherent properties of the variables (mainly if a variable can be deleted or not)

我还没有找到任何关于声明和未声明之间区别的可靠信息,除了它改变了变量的固有属性(主要是变量是否可以删除)

Whether variables are declared or not also changes when the variable is initialised: with var, variables are created and initialised to undefinedbefore any code is executed. Without var, variables don't exist until the code assigning to them is executed (which might be never if assignment is conditional).

变量是否声明也会在变量初始化时发生变化:使用var,在执行任何代码之前创建变量并将其初始化为undefined。如果没有var,变量在执行分配给它们的代码之前不存在(如果分配是有条件的,则可能永远不会存在)。