How to create a CoffeeScript style existential operator in JavaScript?(如何在 JavaScript 中创建 CoffeeScript 风格的存在运算符?)
问题描述
CoffeeScript 将 user?.id
变成
CoffeeScript turns user?.id
into
if (typeof user !== "undefined" && user !== null) {
user.id;
}
是否可以创建一个 JavaScript 函数 exists
来做类似的事情?即
Is it possible to create a JavaScript function exists
that would do something similar? i.e.
exists(user).id
将导致 user.id
或 null
如果一个函数接受另一个参数,即 exists(user, 'id')
会更容易,但这看起来不太好.
It would be easier if a function accepts another parameter, i.e. exists(user, 'id')
, but that wouldn't look as nice.
推荐答案
不,你不能产生这样的功能.问题在于:
No, you can't produce such a function. The problem is that this:
any_function(undeclared_variable)
如果 undeclared_variable
没有在任何地方声明,
将产生一个 ReferenceError.例如,如果您运行此独立代码:
will produce a ReferenceError if undeclared_variable
was not declared anywhere. For example, if you run this stand alone code:
function f() { }
f(pancakes);
你会得到一个 ReferenceError 因为 pancakes
没有在任何地方声明.演示:http://jsfiddle.net/ambiguous/wSZaL/
you'll get a ReferenceError because pancakes
was not declared anywhere. Demo: http://jsfiddle.net/ambiguous/wSZaL/
但是,typeof
operator 可用于尚未声明的内容,因此:
However, the typeof
operator can be used on something that has not been declared so this:
console.log(typeof pancakes);
将简单地在控制台中记录一个 undefined
.演示:http://jsfiddle.net/ambiguous/et2Nv/
will simply log an undefined
in the console. Demo: http://jsfiddle.net/ambiguous/et2Nv/
如果您不介意可能的 ReferenceErrors,那么您的问题中已经有了必要的功能:
If you don't mind possible ReferenceErrors then you already have the necessary function in your question:
function exists(obj, key) {
if (typeof obj !== "undefined" && obj !== null)
return obj[key];
return null; // Maybe you'd want undefined instead
}
或者,由于您不需要能够在此处对未声明的变量使用 typeof
,您可以将其简化为:
or, since you don't need to be able to use typeof
on undeclared variables here, you can simplify it down to:
function exists(obj, key) {
if(obj != null)
return obj[key];
return null;
}
注意对 !=
的更改,undefined == null
为真,即使 undefined === null
不是.
Note the change to !=
, undefined == null
is true even though undefined === null
is not.
这篇关于如何在 JavaScript 中创建 CoffeeScript 风格的存在运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 中创建 CoffeeScript 风格的存在运算符?
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 动态更新多个选择框 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01