如何在JavaScript中创建一个CoffeeScript风格存在操作符? [英] How to create a CoffeeScript style existential operator in JavaScript?
问题描述
CoffeeScript将用户?.id
转换为
if user!==undefined&& user!== null){
user.id;
}
是否可以创建一个JavaScript函数 exists
会做类似的事情吗?即
exists(user).id
会导致 user.id
或 null
如果一个函数接受另一个参数,即 exists(user,'id')
很好。
不,你不能生成这样的函数。问题是:
any_function(undeclared_variable)
$ p $如果
undeclared_variable
没有在任何地方声明,则p>
会产生一个ReferenceError。例如,如果你运行这个独立的代码:
function f(){}
f(pancakes);
你会得到一个ReferenceError,因为
pancakes
没有声明任何地方。演示: http://jsfiddle.net/ambiguous/wSZaL/
但是,
typeof
运算符可用于未声明的内容,因此:console.log(typeof pancakes);
只会在控制台中记录
undefined
。演示: http://jsfiddle.net/ambiguous/et2Nv/
如果你不介意可能的ReferenceErrors那么你已经在你的问题中有必要的功能:
函数存在(obj,key){
if(typeof obj!==undefined&& obj!== null)
return obj [key];
return null; //也许你想要undefined而不是
}
需要能够在未声明的变量上使用
typeof
,您可以将其简化为:function exists(obj,key){
if(obj!= null)
return obj [key];
return null;
}
请注意
!=
,undefined == null
为true,即使undefined === null
CoffeeScript turns
user?.id
intoif (typeof user !== "undefined" && user !== null) { user.id; }
Is it possible to create a JavaScript function
exists
that would do something similar? i.e.exists(user).id
would result in either
user.id
ornull
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)
will produce a ReferenceError if
undeclared_variable
was not declared anywhere. For example, if you run this stand alone code:function f() { } f(pancakes);
you'll get a ReferenceError because
pancakes
was not declared anywhere. Demo: http://jsfiddle.net/ambiguous/wSZaL/However, the
typeof
operator can be used on something that has not been declared so this:console.log(typeof pancakes);
will simply log an
undefined
in the console. Demo: http://jsfiddle.net/ambiguous/et2Nv/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 }
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; }
Note the change to
!=
,undefined == null
is true even thoughundefined === null
is not.这篇关于如何在JavaScript中创建一个CoffeeScript风格存在操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!