javascript 如何删除一个变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16963066/
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-27 06:36:45  来源:igfitidea点击:

How to delete a variable?

javascript

提问by user2389793

Here is my javascript code, I want to delete the variable code so that it has value undefined.

这是我的 javascript 代码,我想删除变量代码,使其具有未定义的值。

var code = $(this).data('code');
var userelm = $(this);

Here I'm doing the check:

我在这里做检查:

if($('.code-1').val()!='' && $('.code-2').val()!='' && $('.code-3').val()!=''){
    if(code==$('.code-1').val()+$('.code-2').val()+$('.code-3').val()){
        $('.overlay').remove();
        $('.code-box').remove();
        $('.close-lock').remove();
        userelm.ajaxloader(); //own function
        userelm.off();
        delete code;
        console.log(code);
        delete userelm;
    }
}

Why does this program not remove the codevariable so it has the value undefined?

为什么这个程序不删除code变量,所以它的值是未定义的?

回答by gpojd

Deletedoes not delete a variable.

删除不会删除变量。

The delete operator removes a property from an object.

delete 运算符从对象中删除属性。

You can try:

你可以试试:

code = null;

回答by Eric Leschinski

Delete a variable in JavaScript:

在 JavaScript 中删除一个变量:

Summary:

概括:

The reason you are having trouble deleting your variable in JavaScript is because JavaScript won't let you. You can't delete anything created by the varcommand unless we pull a rabbit out our bag of tricks.

您在 JavaScript 中删除变量时遇到问题的原因是 JavaScript 不允许您这样做。你不能删除var命令创建的任何东西,除非我们从我们的技巧袋里拿出一只兔子。

The delete command is only for object's properties which were not created with var.

删除命令仅适用于不是用 var 创建的对象的属性。

JavaScript will let you delete a variable created with var under the following conditions:

JavaScript 将允许您在以下条件下删除使用 var 创建的变量:

  1. You are using a javascript interpreter or commandline.

  2. You are using eval and you create and delete your var inside there.

  1. 您正在使用 javascript 解释器或命令行。

  2. 您正在使用 eval 并在其中创建和删除您的 var。

Demo on terminal, Use the delete booor delete(boo)command.A demo with jscommand line terminal let you delete a variable.

在终端上演示,使用delete booordelete(boo)命令。带有js命令行终端的演示可让您删除变量。

el@defiant ~ $ js

js> typeof boo
"undefined"

js> boo
typein:2: ReferenceError: boo is not defined

js> boo=5
5

js> typeof boo
"number"

js> delete(boo)
true

js> typeof boo
"undefined"

js> boo
typein:7: ReferenceError: boo is not defined

If you MUST set your variable to undefined in JavaScript, you have one option:

如果您必须在 JavaScript 中将变量设置为 undefined,您有一个选择:

Demo in javascript page: put this in myjs.html:

javascript页面中的演示:把它放在myjs.html

<html>
<body>
    <script type="text/JavaScript">
        document.write("aliens: " + aliens + "<br>");
        document.write("typeof aliens: " + (typeof aliens) + "<br>");
        var aliens = "scramble the nimitz";
        document.write("found some aliens: " + (typeof aliens) + "<br>");
        document.write("not sayings its aliens but... " + aliens + "<br>");
        aliens = undefined;
        document.write("aliens set to undefined<br>");
        document.write("typeof aliens: " + (typeof aliens) + "<br>");
        document.write("you sure they are gone? " + aliens);
    </script>
</body>
</html>

Open myjs.html with a browser, it prints this:

用浏览器打开 myjs.html,它打印:

aliens: undefined
typeof aliens: undefined
found some aliens: string
not sayings its aliens but... scramble the nimitz
aliens set to undefined
typeof aliens: undefined
you sure they are gone? undefined

WarningWhen you set your variable to undefinedyou are assigning a variable to another variable. If someone poisons the well by running undefined = 'gotcha!', then whenever you set your variable to undefined, it becomes: "gotcha!".

警告当您将变量设置为时,undefined您正在将一个变量分配给另一个变量。如果有人通过运行使井中毒undefined = 'gotcha!',那么每当您将变量设置为 undefined 时,它就会变成:“gotcha!”。

How should we check if a variable has no value?

我们应该如何检查变量是否没有值?

Use null instead of undefined like this:

像这样使用 null 而不是 undefined :

document.write("skittles: " + skittles + "<br>");
document.write("typeof skittles: " + (typeof skittles) + "<br>");
var skittles = 5;
document.write("skittles: " + skittles + "<br>");
document.write("typeof skittles:" + typeof skittles + "<br>");
skittles = null;
document.write("skittles: " + skittles + "<br>");
document.write("typeof skittles: " + typeof skittles);

Which prints:

哪个打印:

skittles: undefined
typeof skittles: undefined
skittles: 5
typeof skittles:number
skittles: null
typeof skittles: object 

If you are not using strict, you can delete variables created like this:

如果您不使用严格,您可以删除这样创建的变量:

<script type="text/JavaScript">
   //use strict
   a = 5;
   document.writeln(typeof a);        //prints number
   delete a;
   document.writeln(typeof a);        //prints undefined
</script>

but if you uncomment use strict, the javascript will not run.

但是如果你取消注释use strict,javascript 将不会运行。

回答by Argon

The following works in strict mode also:

以下也适用于严格模式:

"use strict";

var foo = 1;
console.log(foo);
// 1

foo = (function(){}());
console.log(foo);
// undefined

;)

;)

回答by Tim W

Try this in global scope:

在全局范围内试试这个:

x = 2;
delete window.x;

回答by user23031988

delete doesn't affect variable names

delete 不影响变量名

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

x = 42;         // creates the property x on the global object
var y = 43;     // declares a new variable, y
myobj = {
  h: 4,
  k: 5
};

delete x;       // returns true  (x is a property of the global object and can be deleted)
delete y;       // returns false (delete doesn't affect variable names)
delete Math.PI; // returns false (delete doesn't affect certain predefined properties)
delete myobj.h; // returns true  (user-defined properties can be deleted)

delete myobj;   // returns true  (myobj is a property of the global object, not a variable, so it can be deleted)

回答by Neeraj Bansal

The others answer is quite simple and effective

其他人的回答非常简单有效

code = null;
code = undefined;

But I want to share it's reason also, Why delete code;won't work

但我也想分享它的原因,为什么要删除代码;不会工作

delete is meant to delete properties of objects only. It's never meant (developed) to delete variables.

delete 仅用于删除对象的属性。从来没有打算(开发)删除变量。

var obj = {
  'first' : 10;
}
//Following will print
console.log(obj.first)

delete obj.first;

//Following will print undefined/null/might give error
console.log(obj.first)

Bounus (for developers)

奖金(针对开发人员)

var item = 10;
delete item;
//Following will print 
console.log(item);

//The reason for upper is when we declare variable with var it is of 
//primitive data type and delete won't work.


item = 10;
delete item;
//Following will give reference error
console.log(item);

//The reason for upper is when we declare variable without var it is a 
//property of global 'window' object so delete work.

回答by Neeraj Bansal

Variables created on the fly will be automatically deletedafter there is no more reference to it.

动态创建的变量将在没有更多引用后自动删除

(function(){
  var a = 1;
})(); //a available until here

回答by peyman azizi

because you write varfor define the variable. if you use var can not delete it. you must be write this

因为你写了var来定义变量。如果你使用 var 不能删除它。你一定要写这个

userelm = null;

or don't write var. See this question: How to unset or remove a Javascript variable?

或者不要写var。请参阅此问题:如何取消设置或删除 Javascript 变量?

回答by Vitalii

you don't have to remove var , if you declared it in a function - when function ends, the inner var stops existing. You just don't have to declare variables globally.

您不必删除 var ,如果您在函数中声明它 - 当函数结束时,内部 var 停止存在。您只是不必全局声明变量。

回答by Michal Vlasák

I was not successful with myvariable = null.

我没有成功myvariable = null

But I was successful with myvariable = function(){};

但我成功了 myvariable = function(){};