Javascript 我可以将变量设置为 undefined 或将 undefined 作为参数传递吗?

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

Can I set variables to undefined or pass undefined as an argument?

javascriptundefined

提问by AJ.

I'm a bit confused about JavaScript's undefinedand nullvalues.

我对 JavaScriptundefinednull值有点困惑。

What does if (!testvar)actually do? Does it test for undefinedand nullor just undefined?

什么是if (!testvar)真正做到?它是否测试undefinednull或只是undefined

Once a variable is defined can I clear it back to undefined(therefore deleting the variable)?

一旦定义了变量,我可以将其清除回undefined(因此删除变量)吗?

Can I pass undefinedas a parameter? E.g.:

我可以undefined作为参数传递吗?例如:

function test(var1, var2, var3) {

}

test("value1", undefined, "value2");

回答by bobince

I'm a bit confused about Javascript undefined & null.

我对 Javascript undefined & null 有点困惑。

Don't be confused about null. It generally makes sense and behaves similarly to other scripting languages' concepts of the out-of-band ‘null', ‘nil' or ‘None' objects.

不要对null. 它通常有意义并且行为类似于其他脚本语言的带外“null”、“nil”或“None”对象的概念。

undefined, on the other hand, is a weird JavaScript quirk. It's a singleton object that represents out-of-band values, essentially a second similar-but-different null. It comes up:

undefined,另一方面,是一个奇怪的 JavaScript 怪癖。它是一个表示带外值的单例对象,本质上是第二个类似但不同的null. 它出现:

  1. When you call a function with fewer arguments than the arguments list in the functionstatement lists, the unpassed arguments are set to undefined. You can test for that with eg.:

    function dosomething(arg1, arg2) {
        if (arg2===undefined)
        arg2= DEFAULT_VALUE_FOR_ARG2;
        ...
    }
    

    With this method you can't tell the difference between dosomething(1)and dosomething(1, undefined); arg2will be the same value in both. If you need to tell the difference you can look at arguments.length, but doing optional arguments like that isn't generally very readable.

  2. When a function has no return value;, it returns undefined. There's generally no need to use such a return result.

  3. When you declare a variable by having a var astatement in a block, but haven't yet assigned a value to it, it is undefined. Again, you shouldn't really ever need to rely on that.

  4. The spooky typeofoperator returns 'undefined'when its operand is a simple variable that does not exist, instead of throwing an error as would normally happen if you tried to refer to it. (You can also give it a simple variable wrapped in parentheses, but nota full expression involving a non-existant variable.) Not much use for that, either.

  5. This is the controversial one. When you access a property of an object which doesn't exist, you don't immediately get an error like in every other language. Instead you get an undefinedobject. (And then when you try to use that undefinedobject later on in the script it'll go wrong in a weird way that's much more difficult to track down than if JavaScript had just thrown an error straight away.)

    This is often used to check for the existence of properties:

    if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
       ...do something...
    

    However, because you can assign undefinedlike any other value:

    o.prop= undefined;
    

    that doesn't actually detect whether the property is there reliably. Better to use the inoperator, which wasn't in the original Netscape version of JavaScript, but is available everywhere now:

    if ('prop' in o)
        ...
    
  1. 当您调用参数少于function语句列表中的参数列表的函数时,未传递的参数将设置为undefined。您可以使用例如:

    function dosomething(arg1, arg2) {
        if (arg2===undefined)
        arg2= DEFAULT_VALUE_FOR_ARG2;
        ...
    }
    

    使用这种方法,您无法区分dosomething(1)dosomething(1, undefined); arg2两者的值相同。如果您需要区分差异,您可以查看arguments.length,但执行这样的可选参数通常不是很容易阅读。

  2. 当函数没有时return value;,它返回undefined。一般不需要使用这样的返回结果。

  3. 当您通过var a在块中使用语句来声明变量,但尚未为其赋值时,它是undefined. 同样,你真的不需要依赖它。

  4. 当它的操作数是一个不存在的简单变量时,幽灵typeof操作符返回'undefined',而不是在您尝试引用它时通常会发生的错误。(你也可以给它一个用括号括起来的简单变量,但不是一个包含不存在变量的完整表达式。)这也没什么用。

  5. 这是有争议的。当您访问一个不存在的对象的属性时,您不会像其他语言一样立即收到错误消息。相反,您会得到一个undefined对象。(然后当您稍后undefined在脚本中尝试使用该对象时,它会以一种奇怪的方式出错,这比 JavaScript 直接抛出错误更难追踪。)

    这通常用于检查属性是否存在:

    if (o.prop!==undefined) // or often as truthiness test, if (o.prop)
       ...do something...
    

    但是,因为您可以undefined像任何其他值一样分配:

    o.prop= undefined;
    

    这实际上并不能检测该财产是否可靠地存在。最好使用in运算符,它不在 JavaScript 的原始 Netscape 版本中,但现在随处可用:

    if ('prop' in o)
        ...
    

In summary, undefinedis a JavaScript-specific mess, which confuses everyone. Apart from optional function arguments, where JS has no other more elegant mechanism, undefinedshould be avoided. It should never have been part of the language; nullwould have worked just fine for (2) and (3), and (4) is a misfeature that only exists because in the beginning JavaScript had no exceptions.

总之,undefined是一个 JavaScript 特有的混乱,让每个人都感到困惑。除了可选的函数参数之外,JS 没有其他更优雅的机制,undefined应该避免。它不应该成为语言的一部分;null对于 (2) 和 (3) 本来可以很好地工作,而 (4) 是一个错误功能,它仅存在于 JavaScript 开始时没有异常。

what does if (!testvar)actually do? Does it test for undefined and null or just undefined?

什么if (!testvar)实际上做?它是否测试未定义和空值或只是未定义?

Such a ‘truthiness' test checks against false, undefined, null, 0, NaNand empty strings. But in this case, yes, it is really undefinedit is concerned with. IMO, it should be more explicit about that and say if (testvar!==undefined).

这样的“感实性”对测试检查falseundefinednull0NaN和空字符串。但是在这种情况下,是的,它确实与undefined它有关。IMO,应该更明确地说if (testvar!==undefined)

once a variable is defined can I clear it back to undefined (therefore deleting the variable).

一旦定义了变量,我可以将其清除回未定义(因此删除变量)。

You can certainly assign undefinedto it, but that won't delete the variable. Only the delete object.propertyoperator really removes things.

您当然可以分配undefined给它,但这不会删除变量。只有delete object.property操作员才能真正移除东西。

deleteis really meant for properties rather than variables as such. Browsers will let you get away with straight delete variable, but it's not a good idea and won't work in ECMAScript Fifth Edition's strict mode. If you want to free up a reference to something so it can be garbage-collected, it would be more usual to say variable= null.

delete真正用于属性而不是变量本身。浏览器会让你摆脱直接delete variable,但这不是一个好主意,并且在 ECMAScript Fifth Edition 的严格模式下不起作用。如果你想释放对某物的引用以便它可以被垃圾收集,通常说variable= null.

can I pass undefined as a parameter?

我可以将 undefined 作为参数传递吗?

Yes.

是的。

回答by Tatu Ulmanen

You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just definedit to something.

你不能(不应该?)将任何东西定义为未定义,因为变量将不再是未定义的——你只是定义为某个东西。

You cannot (should not?) pass undefinedto a function. If you want to pass an empty value, use nullinstead.

你不能(不应该?)传递undefined给一个函数。如果要传递空值,请null改用。

The statement if(!testvar)checks for boolean true/false values, this particular one tests whether testvarevaluates to false. By definition, nulland undefinedshouldn't be evaluated neither as trueor false, but JavaScript evaluates nullas false, and gives an error if you try to evaluate an undefined variable.

该语句if(!testvar)检查布尔真/假值,这个特定的测试是否testvar评估为false。根据定义,null并且undefined不应该既不评估为truefalse,但JavaScript的求值nullfalse,如果你试图评估一个未定义的变量给出了一个错误。

To properly test for undefinedor null, use these:

要正确测试undefinednull,请使用这些:

if(typeof(testvar) === "undefined") { ... }

if(testvar === null) { ... }

回答by Todd

The basic difference is that undefinedand nullrepresent different concepts.

基本的区别在于undefinednull代表不同的概念。

If only nullwas available, you would not be able to determine whether nullwas set intentionally as the value or whether the value has not been set yet unless you used cumbersome error catching: eg

如果 onlynull可用,您将无法确定null是有意设置为值还是尚未设置该值,除非您使用了繁琐的错误捕获:例如

var a;

a == null; // This is true
a == undefined; // This is true;
a === undefined; // This is true;

However, if you intentionally set the value to null, strict equality with undefinedfails, thereby allowing you to differentiate between nulland undefinedvalues:

但是,如果您有意将值设置为null,则严格相等与undefined失败,从而允许您区分nullundefined值:

var b = null;
b == null; // This is true
b == undefined; // This is true;
b === undefined; // This is false;

Check out the reference here instead of relying on people dismissively saying junk like "In summary, undefined is a JavaScript-specific mess, which confuses everyone". Just because you are confused, it does not mean that it is a mess.

查看这里的参考资料,而不是依赖人们轻蔑地说像“总之, undefined 是 JavaScript 特定的混乱,让每个人都感到困惑”之类的不屑一顾的说法。仅仅因为你感到困惑,并不意味着它是一团糟。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

This behaviour is also not specific to JavaScript and it completes the generalised concept that a boolean result can be true, false, unknown (null), no value (undefined), or something went wrong (error).

这种行为也不是 JavaScript 特有的,它完善了布尔结果可以是truefalse、未知 ( null)、 无值 ( undefined) 或出现问题 ( error)的通用概念。

http://en.wikipedia.org/wiki/Undefined_value

http://en.wikipedia.org/wiki/Undefined_value

回答by rahul

The best way to check for a null values is

检查空值的最佳方法是

if ( testVar !== null )
{
    // do action here
}

and for undefined

对于未定义

if ( testVar !== undefined )
{
    // do action here
}

You can assign a avariable with undefined.

您可以使用 undefined 分配变量。

testVar = undefined;
//typeof(testVar) will be equal to undefined.

回答by rahul

YES, you can,because undefined is definedas undefined.

是的,你可以,因为 undefined 被定义为 undefined。

console.log(
   /*global.*/undefined === window['undefined'] &&
   /*global.*/undefined === (function(){})() &&
   window['undefined']  === (function(){})()
) //true

your case:

你的情况:

test("value1", undefined, "value2")

you can also createyour own undefined variable:

您还可以创建自己的未定义变量:

Object.defineProperty(this, 'u', {value : undefined});
console.log(u); //undefined

回答by Skilldrick

To answer your first question, the not operator (!) will coerce whatever it is given into a boolean value. So null, 0, false, NaNand ""(empty string) will all appear false.

要回答您的第一个问题,not 运算符 ( !) 将强制将其赋予的任何内容转换为布尔值。因此null, 0, false,NaN""(空字符串) 都将显示为 false。

回答by Eric Leschinski

JavaScript, how to set a variable to undefined on commandline:

JavaScript,如何在命令行上将变量设置为未定义:

Set a variable to undefined in the jsjavascript command line terminal that comes with Java on Ubuntu 12.10.

js在 Ubuntu 12.10 上的 Java 附带的javascript 命令行终端中将变量设置为 undefined 。

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 set a variable to undefined in a javascript:

如果您在 javascript 中将变量设置为 undefined:

Put this in myjs.html:

把它放在 myjs.html 中:

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

It prints this:

它打印这个:

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

WARNING! When setting your variable to undefined you are setting your variable to another variable. If some sneaky person runs undefined = 'rm -rf /';then whenever you set your variable to undefined, you will receive that value.

警告!将变量设置为 undefined 时,您将变量设置为另一个变量。如果某个偷偷摸摸的人跑了,undefined = 'rm -rf /';那么每当您将变量设置为 undefined 时,您都会收到该值。

You may be wondering how I can output the undefined value aliens at the start and have it still run. It's because of javascript hoisting: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

您可能想知道如何在开始时输出未定义值的外星人并让它继续运行。这是因为 javascript 提升:http: //www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

回答by Cqq Cqq

Try this:

尝试这个:

// found on UglifyJS
variable = void 0;

回答by rdans

Just for fun, here's a fairly safe way to assign "unassigned" to a variable. For this to have a collision would require someone to have added to the prototype for Object with exactly the same name as the randomly generated string. I'm sure the random string generator could be improved, but I just took one from this question: Generate random string/characters in JavaScript

只是为了好玩,这里有一种相当安全的方法将“未分配”分配给变量。为了产生碰撞,需要有人将与随机生成的字符串同名的对象添加到原型中。我确信随机字符串生成器可以改进,但我只是从这个问题中获取了一个:在 JavaScript 中生成随机字符串/字符

This works by creating a new object and trying to access a property on it with a randomly generated name, which we are assuming wont exist and will hence have the value of undefined.

这通过创建一个新对象并尝试使用随机生成的名称访问其上的属性来工作,我们假设它不存在,因此具有未定义的值。

function GenerateRandomString() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 50; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

var myVar = {}[GenerateRandomString()];

回答by Guffa

The for if (something)and if (!something)is commonly used to check if something is defined or not defined. For example:

for if (something)andif (!something)通常用于检查某些内容是否已定义或未定义。例如:

if (document.getElementById)

The identifier is converted to a boolean value, so undefinedis interpreted as false. There are of course other values (like 0 and '') that also are interpreted as false, but either the identifier should not reasonably have such a value or you are happy with treating such a value the same as undefined.

标识符被转换为布尔值,因此undefined被解释为false。当然还有其他值(如 0 和 '')也被解释为false,但是标识符不应该合理地具有这样的值,或者您很高兴将这样的值视为未定义。

Javascript has a deleteoperator that can be used to delete a member of an object. Depending on the scope of a variable (i.e. if it's global or not) you can delete it to make it undefined.

Javascript 有一个delete运算符,可用于删除对象的成员。根据变量的范围(即它是否为全局变量),您可以将其删除以使其未定义。

There is no undefinedkeyword that you can use as an undefined literal. You can omit parameters in a function call to make them undefined, but that can only be used by sending less paramters to the function, you can't omit a parameter in the middle.

没有undefined可以用作未定义文字的关键字。您可以在函数调用中省略参数以使其未定义,但这只能通过向函数发送较少的参数来使用,您不能在中间省略参数。