我将举例解释:

猫王运算符(?:)

“猫王运算符”是缩写 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

当前回答

你可以使用逻辑'OR'操作符来代替Elvis操作符:

例如displayname = user.name || "匿名"。

但Javascript目前还不具备其他功能。如果你想要一种替代语法,我建议你看看CoffeeScript。它有一些类似于你要找的东西的简写。

例如存在操作符

zip = lottery.drawWinner?().address?.zipcode

功能快捷键

()->  // equivalent to function(){}

性感的函数调用

func 'arg1','arg2' // equivalent to func('arg1','arg2')

还有多行注释和类。显然,你必须将此编译为javascript或插入到页面中,作为<script type='text/coffeescript>',但它增加了很多功能:)。使用<script type='text/coffeescript'>实际上只用于开发而不是生产。

其他回答

我阅读了这篇文章(https://www.beyondjava.net/elvis-operator-aka-safe-navigation-javascript-typescript),并使用代理修改了解决方案。

function safe(obj) {
    return new Proxy(obj, {
        get: function(target, name) {
            const result = target[name];
            if (!!result) {
                return (result instanceof Object)? safe(result) : result;
            }
            return safe.nullObj;
        },
    });
}

safe.nullObj = safe({});
safe.safeGet= function(obj, expression) {
    let safeObj = safe(obj);
    let safeResult = expression(safeObj);

    if (safeResult === safe.nullObj) {
        return undefined;
    }
    return safeResult;
}

你这样称呼它:

safe.safeGet(example, (x) => x.foo.woo)

如果表达式在其路径上遇到null或undefined,则结果将是未定义的。你可以随意修改Object原型!

Object.prototype.getSafe = function (expression) {
    return safe.safeGet(this, expression);
};

example.getSafe((x) => x.foo.woo);

Javascript的逻辑OR运算符短路,可以取代你的“猫王”运算符:

var displayName = user.name || "Anonymous";

然而,据我所知,没有与你的?相当的。操作符。

这个问题困扰了我很长一段时间。我必须想出一个解决方案,一旦我们得到猫王运算符或其他东西,就可以很容易地迁移。

这就是我用的;适用于数组和对象

把这个放到tools.js文件里

// this will create the object/array if null
Object.prototype.__ = function (prop) {
    if (this[prop] === undefined)
        this[prop] = typeof prop == 'number' ? [] : {}
    return this[prop]
};

// this will just check if object/array is null
Object.prototype._ = function (prop) {
    return this[prop] === undefined ? {} : this[prop]
};

使用的例子:

let student = {
    classes: [
        'math',
        'whatev'
    ],
    scores: {
        math: 9,
        whatev: 20
    },
    loans: [
        200,
        { 'hey': 'sup' },
        500,
        300,
        8000,
        3000000
    ]
}

// use one underscore to test

console.log(student._('classes')._(0)) // math
console.log(student._('classes')._(3)) // {}
console.log(student._('sports')._(3)._('injuries')) // {}
console.log(student._('scores')._('whatev')) // 20
console.log(student._('blabla')._('whatev')) // {}
console.log(student._('loans')._(2)) // 500 
console.log(student._('loans')._(1)._('hey')) // sup
console.log(student._('loans')._(6)._('hey')) // {} 

// use two underscores to create if null

student.__('loans').__(6)['test'] = 'whatev'

console.log(student.__('loans').__(6).__('test')) // whatev

好吧,我知道这使代码有点难以阅读,但这是一个简单的一行解决方案,工作出色。我希望它能帮助到一些人:)

我个人使用

function e(e,expr){try{return eval(expr);}catch(e){return null;}};

例如,safe get:

var a = e(obj,'e.x.y.z.searchedField');

我创建了一个软件包,使它更容易使用。

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';