使用||在javascript中初始化对象操作者 [英] Init object in javascript using || operator

查看:83
本文介绍了使用||在javascript中初始化对象操作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我在javascript代码中看到类似这样的内容:

Sometimes I see in javascript code something like this:

var myObj = myObj || {};

那么,这里究竟发生了什么?我想|| operator返回true或false,但它不正确。

So, what actually happen here? I suppose || operator returns true or false, but it's not correct.

推荐答案

|| 运算符如果计算结果为则返回左操作数如果为true,则计算并返回正确的操作数。换句话说, a || b 相当于 a? a:b ,但 a 仅评估一次。

The || operator returns the left operand if it evaluates as true, otherwise it evaluates and returns the right operand. In other words, a || b is equivalent to a ? a : b except that a is only evaluated once.

这篇关于使用||在javascript中初始化对象操作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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