我将举例解释:
猫王运算符(?:)
“猫王运算符”是缩写
Java的三元运算符。一个
这很方便的例子是
返回一个“合理的默认值”
如果表达式解析为false或
null。一个简单的例子是这样的
这样的:
def gender = user.male ? "male" : "female" //traditional ternary operator usage
def displayName = user.name ?: "Anonymous" //more compact Elvis operator
安全导航操作员(?.)
使用安全导航操作符
来避免NullPointerException。
通常当你有一个参考
您可能需要验证的对象
在访问前它不是空的
对象的方法或属性。
为了避免这种情况,安全航行
运算符将简单地返回null
而不是抛出异常,比如
所以:
def user = User.find( "admin" ) //this might be null if 'admin' does not exist
def streetName = user?.address?.street //streetName will be null if user or user.address is null - no NPE thrown
我创建了一个软件包,使它更容易使用。
NPM jsdig
Github jsdig
你可以处理简单的东西,比如and object:
const world = {
locations: {
europe: 'Munich',
usa: 'Indianapolis'
}
};
world.dig('locations', 'usa');
// => 'Indianapolis'
world.dig('locations', 'asia', 'japan');
// => 'null'
或者更复杂一点:
const germany = () => 'germany';
const world = [0, 1, { location: { europe: germany } }, 3];
world.dig(2, 'location', 'europe') === germany;
world.dig(2, 'location', 'europe')() === 'germany';
我创建了一个软件包,使它更容易使用。
NPM jsdig
Github jsdig
你可以处理简单的东西,比如and object:
const world = {
locations: {
europe: 'Munich',
usa: 'Indianapolis'
}
};
world.dig('locations', 'usa');
// => 'Indianapolis'
world.dig('locations', 'asia', 'japan');
// => 'null'
或者更复杂一点:
const germany = () => 'germany';
const world = [0, 1, { location: { europe: germany } }, 3];
world.dig(2, 'location', 'europe') === germany;
world.dig(2, 'location', 'europe')() === 'germany';
这是一个简单的猫王运算符等价:
function elvis(object, path) {
return path ? path.split('.').reduce(function (nestedObject, key) {
return nestedObject && nestedObject[key];
}, object) : object;
}
> var o = { a: { b: 2 }, c: 3 };
> elvis(o)
{ a: { b: 2 }, c: 3 }
> elvis(o, 'a');
{ b: 2 }
> elvis(o, 'a.b');
2
> elvis(o, 'x');
undefined