在JavaScript中Ruby的|| =(或等于)? [英] Ruby's ||= (or equals) in JavaScript?

查看:71
本文介绍了在JavaScript中Ruby的|| =(或等于)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢Ruby的 || = 机制。如果变量不存在或 nil ,则创建它并将其设置为等于:

I love Ruby's ||= mechanism. If a variable doesn't exist or is nil, then create it and set it equal to something:

amount # is nil
amount ||= 0 # is 0
amount ||= 5 # is 0

我现在需要在JavaScript中做类似的事情。什么是惯例或正确的方法来做到这一点?我知道 || = 是无效的语法。处理它的两种明显方法是:

I need to do something similar in JavaScript now. What's the convention or proper way to do this? I know ||= is not valid syntax. 2 obvious ways to handle it are:

window.myLib = window.myLib || {};

// or

if (!window.myLib)
  window.myLib = {};


推荐答案

两者都绝对正确,但如果您正在寻找在ruby中像 || = 一样的东西。第一种方法是 variable = variable || {} 是你要找的那个:)

Both are absolutely correct, but if you are looking for something that works like ||= in ruby. The first method which is variable = variable || {} is the one you are looking for :)

这篇关于在JavaScript中Ruby的|| =(或等于)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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