Javascript从函数中分配属性

时间:2015-03-21 02:16:11

标签: javascript

我不知道这是否可行,但我想要完成的是从一个被调用的函数中为一个对象赋一个属性值。当运行active的函数时,我想在创建对象时分配true或false作为其值。我们能用这种方式使用自执行功能吗?

这是我的代码,仍在进行中,但是有哪些东西能在javascript中完成吗?

        graphObj.list.push({
            name: graphData[i].name,
            value: Math.floor(graphData[i].time / graphData[graphData.length - 1] * 100),
            str: graphData[i].strTime
            active: (function(){
                if (activeActivityName != "" && graphData[i].name == activeActivityName){
                    return true;
                } else {
                    return false;
                }
            })
        });

2 个答案:

答案 0 :(得分:2)

我真的很想阻止你在这里使用IIFE,因为我坚信这是对IIFE的不当使用。那么如何只分配条件的结果:

graphObj.list.push({
    name: graphData[i].name,
    value: Math.floor(graphData[i].time / graphData[graphData.length - 1] * 100),
    str: graphData[i].strTime,
    active: (activeActivityName != "" && graphData[i].name == activeActivityName)
});

答案 1 :(得分:0)

为什么要在调用函数时使用立即调用的函数表达式。

function isActive(activeActivityName, graphData, i) {
    if (activeActivityName != "" && graphData[i].name == activeActivityName) {
        return true;
    } else {
        return false;
    }
}

graphObj.list.push({
    name: graphData[i].name,
    value: Math.floor(graphData[i].time / graphData[graphData.length - 1] * 100),
    str: graphData[i].strTime,
    active: isActive(activeActivityName, graphData, i)
});
相关问题