如果 - 否则,对象未定义时的最佳做法

时间:2013-04-11 20:08:34

标签: javascript

我想知道我的代码是否接近是好的,我想:

  1. 检查对象是否存在
  2. 如果不存在,请创建并分配属性
  3. 如果已存在则只分配属性
  4. 我现在拥有的是以下代码,但我不喜欢两次写同一行

    function doSomething(_whatever){
        if(typeof someobject === "undefined"){
            someobject = { //dont exist
                profile : "some value",
                status : []
            }
    
            someobject.status.push(_whatever);
        }else{
            someobject.status.push(_whatever); //because already exist
        }
    }
    

    编写此代码段的更好方法是什么?或者做得更好,重复性更低?

    提前致谢

    ------原始功能

    function addPerson(_person){
        var people = Iee.dashboard.analytics.data.people.data;      
        if(typeof people[_person.Id_Emp] === "undefined"){
            people[_person.Id_Emp] = {
                profile : _person,
                status : []
            }
    
            people[_person.Id_Emp].status.push({Id_Emp : _person.Id_Emp, status : _person.Estatus1, estatusby : _person.Centro_de_trabajo});
        }else{
            people[_person.Id_Emp].status.push({Id_Emp : _person.Id_Emp, status : _person.Estatus1, estatusby : _person.Centro_de_trabajo});
        }
    
        addBlackList(_person);
    }
    

3 个答案:

答案 0 :(得分:4)

执行此操作的常用方法是进行冗余检查:

someobject = someobject || {
    project:"some value",
    status:[]
};

答案 1 :(得分:4)

简化代码

function addPerson(_person){
        var people = Iee.dashboard.analytics.data.people.data;      
        people[_person.Id_Emp] = people[_person.Id_Emp] || {
                profile : _person,
                status : []
            };

            people[_person.Id_Emp].status.push({Id_Emp : _person.Id_Emp, status : _person.Estatus1, estatusby : _person.Centro_de_trabajo});

        addBlackList(_person);
    }

答案 2 :(得分:1)

在这种情况下,你希望它是一个对象或未定义的,而不是一个字符串,一个数字等,所以你可以检查它是否有一个真值。

function addPerson(_person) {
    var people = Iee.dashboard.analytics.data.people.data,
        person = people[_person.Id_Emp];

    if (!person) person = {
        profile: _person,
        status: []
    };
    person.status.push({
        Id_Emp: _person.Id_Emp, 
        status: _person.Estatus1, 
        estatusby: _person.Centro_de_trabajo
    });

    addBlackList(_person);
}

这应该比其他答案中提到的冗余检查略好一些,因为如果(truthy)值尚未存在,它只会为变量赋值。

只是为了好玩,这是一个超精简版:

function addPerson(_person) {
    var people = Iee.dashboard.analytics.data.people.data, id = _person.Id_Emp;

    (people[id] || { profile: _person, status: [] }).status.push({
        Id_Emp: id, status: _person.Estatus1, estatusby: _person.Centro_de_trabajo
    });
    addBlackList(_person);
}
相关问题