这是我的javascript代码,我想删除变量code,这样它就有了未定义的值。
var code = $(this).data('code');
var userelm = $(this);下面是我的检查:
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;
}
}为什么这个程序不删除code变量,所以它的值是未定义的?
发布于 2013-06-06 21:16:50
发布于 2014-01-09 03:00:21
删除JavaScript中的变量:
摘要:
在JavaScript中删除变量时遇到问题的原因是JavaScript不允许这样做。您不能删除由var命令创建的任何内容,除非我们从我们的小把戏中拉出一只兔子。
delete命令仅适用于不是使用var创建的对象属性。
在以下情况下,JavaScript将允许您删除使用var创建的变量:
您正在使用javascript解释器或commandline.
在终端上,使用delete boo delete(boo) 或delete(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如果必须在JavaScript中将变量设置为undefined,则有一个选择:
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>使用浏览器打开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警告当您将变量设置为undefined时,您正在将一个变量赋给另一个变量。如果有人通过运行undefined = 'gotcha!'来毒害油井,那么每当您将变量设置为undefined时,它就会变成:“明白了!”
我们应该如何检查一个变量是否没有值?
使用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);打印的内容:
skittles: undefined
typeof skittles: undefined
skittles: 5
typeof skittles:number
skittles: null
typeof skittles: object 如果你没有使用,你可以删除像这样创建的变量:
<script type="text/JavaScript">
//use strict
a = 5;
document.writeln(typeof a); //prints number
delete a;
document.writeln(typeof a); //prints undefined
</script>但是如果您取消对use strict的注释,javascript将不会运行。
发布于 2014-01-23 10:08:58
在全局范围内尝试此操作:
x = 2;
delete window.x;https://stackoverflow.com/questions/16963066
复制相似问题