javascript 你能在变量声明中添加条件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11250449/
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
Can you add a condition to a variable declaration?
提问by Kayote
This doesn't make sense to me, but I have a feeling I saw a code using this:
这对我来说没有意义,但我有一种感觉,我看到了一个使用这个的代码:
var abc = def || ghi;
My question is, is this valid? Can we add a condition to a variable declaration? I imagine the answer is no but I have this at the back of my mind that I saw something similar in code once.
我的问题是,这有效吗?我们可以在变量声明中添加条件吗?我想答案是否定的,但我想我曾经在代码中看到过类似的东西。
回答by Denys Séguret
This gives to abc
the value of def
if it isn't falsy (i.e. not false
, null
, undefined
, 0
or an empty string), or the value of ghi
if not.
这得到abc
的值def
,如果它不是falsy(即不false
,null
,undefined
,0
或空字符串),或的值ghi
如果不是。
This is equivalent to:
这相当于:
var abc;
if (def) abc = def;
else abc = ghi;
This is commonly used for options:
这通常用于选项:
function myfunc (opts) {
var mything = opts.mything || "aaa";
}
If you call myfunc({mything:"bbb"})
it uses the value you give. It uses "aaa"
if you provide nothing.
如果您调用myfunc({mything:"bbb"})
它,则使用您提供的值。"aaa"
如果你什么都不提供,它就会使用。
In this case, in order to let the caller wholly skip the parameter, we could also have started the function with
在这种情况下,为了让调用者完全跳过参数,我们也可以用
opts = opts || {};
回答by epascarello
The code var abc = def || ghi;
代码变量 abc = def || ghi;
is the same thing as
是一样的
if (def) { //where def is a truthy value
var abc = def;
} else {
abc = ghi;
}
You want a condition like an if statement?
你想要一个像 if 语句这样的条件吗?
if (xxx==="apple") {
var abc = def;
} else {
abc = ghi;
}
which as written as a ternary operator is:
写成三元运算符是:
var abc = (xxx==="apple") ? def : ghi;
回答by Jashwant
Yes, you can add condition to variable declaration
是的,您可以在变量声明中添加条件
You can use it like this,
你可以像这样使用它,
function greet(person) {
var name = person || 'anonymouse';
alert('Hello ' + name);
}
greet('jashwant');
greet();?
回答by Praveen Kumar Purushothaman
OKay, see, it is something like, you either check if one is true. The true one will be returned. :)
好吧,看,这就像,你要么检查一个是不是真的。真正的会回来的。:)
var abc = def || ghi;
Is equivalent to:
相当于:
var abc = return (def == true) or (ghi == true)