Javascript || 或带有未定义变量的运算符

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

Javascript || or operator with a undefinded variable

javascript

提问by bryan sammon

I have been doing some reading lately one article I read was from Opera.

我最近一直在读一篇文章,我读过一篇来自 Opera 的文章。

http://dev.opera.com/articles/view/javascript-best-practices/

http://dev.opera.com/articles/view/javascript-best-practices/

In that article they write this:

在那篇文章中,他们写道:

Another common situation in JavaScript is providing a preset value for a variable if it is not defined, like so:

JavaScript 中的另一种常见情况是为未定义的变量提供预设值,如下所示:

if(v){
  var x = v;
} else {
  var x = 10;
}

The shortcut notation for this is the double pipe character:

对此的快捷表示法是双管道字符:

var x = v || 10;

For some reason I cant get this to work for me. Is it really possible to check to see if v is defined, if not x = 10?

出于某种原因,我无法让它为我工作。是否真的可以检查是否定义了 v,如果没有定义 x = 10?

--Thanks. Bryan

- 谢谢。布莱恩

回答by user113716

That Opera article gives a poor description of what is happening.

那篇 Opera 文章对正在发生的事情的描述很差。

While it is true that xwill get the value of 10if vis undefined. It is also true that xwill be 10if vhas any"falsey" value.

虽然确实x会得到10if的值vundefined。这也是事实,x将是10,如果v任何“falsey”值。

The "falsey" values in javascript are:

javascript 中的“falsey”值是:

  • 0
  • null
  • undefined
  • NaN
  • ""(empty string)
  • false
  • 0
  • null
  • undefined
  • NaN
  • ""(空字符串)
  • false

So you can see that there are many cases in which xwill be set to 10besides just undefined.

所以你可以看到,除了 just 之外,还有很多情况x会被设置为。10undefined

Here's some documentationdetailing the logical operators. (This one is the "logical OR".) It gives several examples of its usage for such an assignment.

这是一些详细介绍逻辑运算符的文档。(这是“逻辑 OR”。)它给出了几个用于此类赋值的示例。

Quick example: http://jsfiddle.net/V76W6/

快速示例:http: //jsfiddle.net/V76W6/

var v = 0;

var x = v || 10;

alert( x ); // alerts 10

Assign vany of the falsey values that I indicated above, and you'll get the same result.

分配v我上面指出的任何错误值,您将得到相同的结果。

回答by PleaseStand

var x = v || 10;

That operator (the "logical" or "short-circuit" OR operator) would normally check the value of v, and if it is a "falsy" value (i.e.it would fail as a condition used in an if statement), 10becomes the value of x, otherwise vdoes (and if 10were a function, it would never be executed).

该运算符(“逻辑”或“短路” OR 运算符)通常会检查 的值v,如果它是“假”值(它会作为 if 语句中使用的条件失败),则10成为值of x,否则v执行(如果10是函数,则永远不会执行)。

undefined, null, and 0are all examples of falsy values that a variable can hold (yes, even the first one), and the operator (or if statement) acts accordingly. In contrast, all objects and arrays (not including null) are "truthy" values, which allows for such things as this (used in the Google Analytics tracker code):

undefined, null, 和0都是变量可以保存的假值的例子(是的,即使是第一个),并且运算符(或 if 语句)会相应地起作用。相比之下,所有对象和数组(不包括 null)都是“真实”值,这允许这样的事情(在 Google Analytics 跟踪器代码中使用):

var _gaq = _gaq || []; // Makes a new array _gaq if it is not already there

However, if the referenced variable is not even declaredanywhere within the scope chain, then a JavaScript exception will occur.

然而,如果引用的变量甚至没有在作用域链中的任何地方声明,那么就会发生 JavaScript 异常。

One way to avoid this is by declaring all your global variables from the start:

避免这种情况的一种方法是从一开始就声明所有全局变量:

var iAmAGlobalVariable;  // Holds the value undefined by default

If this is not possible, you should use the typeofoperator. It does not attempt to evaluate its operand, and thus an exception will not occur:

如果这是不可能的,您应该使用typeof运算符。它不会尝试评估其操作数,因此不会发生异常:

var x;
if(typeof v != 'undefined' && v) {
    x = v;
} else {
    x = 10;
}

Or even better, if you know that the variable would be a global variable, you can treat it as a property of the global (window) object:

或者更好的是,如果您知道该变量将是一个全局变量,则可以将其视为全局(窗口)对象的一个​​属性:

var x = window.v || 10;

回答by Thai

If vevaluates to false (for example, 0, null, false) then it won't work. You can manually check for undefined:

如果v计算结果为 false(例如,0, null, false),则它将不起作用。您可以手动检查未定义:

var x = v !== undefined ? v : 10;

回答by ScottLinenberger

I would use triple equals with ternary in a function for this.

为此,我会在函数中使用三元等于三元。

function myTest(x){
 return x === undefined ? true: false;
}    

Only returns true if x is undefined

仅当 x 未定义时才返回真

See (http://www.impressivewebs.com/why-use-triple-equals-javascipt/) and (http://jsfiddle.net/V76W6/)

请参阅(http://www.impressivewebs.com/why-use-triple-equals-javascipt/)和(http://jsfiddle.net/V76W6/

回答by Franz Payer

I would just use a try-catch

我只会使用 try-catch

var x = 0;

try
{
    x = v;
}
catch(err)
{
    x = 10;
}

回答by Eric Fortis

Here is how to get it working:

这是让它工作的方法:

var v;         //declare v as undefined
//  v = 5;     //if uncommented x will be 5   

var x = v || 10;
alert(x);      //output: 10

http://jsfiddle.net/uLLtu/1/

http://jsfiddle.net/uLLtu/1/