你能为变量声明添加一个条件吗? [英] Can you add a condition to a variable declaration?

查看:153
本文介绍了你能为变量声明添加一个条件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这对我来说没有意义,但我有一种感觉,我看到了一个代码使用它:

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.

推荐答案

这给 abc def 的值,如果它不是假的(即不是 false) null undefined 0 或空字符串),或 ghi 的值,如果不是。

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.

这相当于:

var abc;
if (def) abc = def;
else abc = ghi;

这通常用于选项:

function myfunc (opts) {
    var mything = opts.mything || "aaa";
}

如果你打电话给 myfunc({mything:bbb })它使用你给出的值。如果你什么都不提供,它会使用aaa

If you call myfunc({mything:"bbb"}) it uses the value you give. It uses "aaa" if you provide nothing.

在这种情况下,为了让来电者完全跳过参数,我们也可以用

In this case, in order to let the caller wholly skip the parameter, we could also have started the function with

opts = opts || {};

这篇关于你能为变量声明添加一个条件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆