如何有条件地向javascript对象文字添加属性 [英] How to conditionally add properties to a javascript object literal

查看:42
本文介绍了如何有条件地向javascript对象文字添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作以满足代码生成器的要求(具体来说,是Sencha Cmd).

I am trying to do the following to satisfy the requirements of a code builder (Sencha Cmd to be specific).

这是我需要做的本质.关键因素是函数体必须以对象文字的返回结尾.由于构建器中的限制,我无法返回变量.因此,如果参数'includeB'为true,如何在下面的伪代码处添加属性'b',但如果为false,则不添加属性ALL.即b == undefined或b == null不允许.

This is the essence I what I need to do. The critical factor is that the function body MUST end with a return of an object literal. I cant return a variable due to restrictions in the builder. So, how to add a property 'b' at the point of the pseudo code below if the parameter 'includeB' is true, but NOT add a property AT ALL if it is false. ie b==undefined or b==null is not allowed.

也许不可能.

function create(includeB) {
        // Can have code here but the final thing MUST be a return of the literal.
        // ...
    return {
        a : 1
        // pseudo code:
        // if (includeB==true) then create a property called b 
        // and assign a value of 2 to it. 
        // Must be done right here within this object literal
    }
}

var obj = create(false);
// obj must have property 'a' ONLY

var obj = create(true);
// obj must have properties 'a' and 'b'

感谢阅读和考虑,

墨累

推荐答案

您已经展示了构造函数的用例,而不是使用对象文字:

You've pretty much shown a use case for a constructor function instead of using an object literal:

function CustomObject(includeB) {
    this.a = 1;
    if (includeB) {
        this.b = 2;
    }
}

//has `a` only
var obj1 = new CustomObject(false);

//has `a` and `b`
var obj2 = new CustomObject(true);


重新阅读您的问题后,您似乎对修改该功能的访问权限受到限制.如果我正确理解了您的问题,则只能更改脚本的一小部分:


After re-reading your question it appears that you've got limited access in modifying the function. If I'm understanding your question correctly you can only change a limited portion of the script:

function create(includeB) {
    // modifications may be done here

    // the rest may not change
    return {
        a : 1
    }
}

var obj = create(false);
// obj must have property 'a' ONLY

var obj = create(true);
// obj must have properties 'a' and 'b'

如果是这种情况,那么您可以简单地跳过该函数的后面部分:

If that's the case, then you could simply skip the later part of the function:

function create(includeB) {
    if (includeB) {
        return {
            a: 1,
            b: 2
        };
    }
    return {
        a: 1
    };
}

这篇关于如何有条件地向javascript对象文字添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆