如何定义条件数组元素? 我想这样做:

const cond = true;
const myArr = ["foo", cond && "bar"];

这正如预期的那样工作,结果是["foo", "bar"],但如果我将cond设置为false,我得到以下结果:["foo", false]

如何定义具有条件元素的数组?


当前回答

替代方法:预过滤填充而不是后过滤:

const populate = function(...values) {
    return values.filter(function(el) {
        return el !== false
    });
};

console.log(populate("foo", true && "bar", false && "baz"))

返回

(2) ["foo", "bar"]

我知道这不能解决速记符号(因为无论你怎么尝试,它都不会起作用),但它接近于那个。

其他回答

如果你真的想把它作为一行,你可以使用:

const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);

有几种不同的方法,但这种方法并不适用于Javascript。

最简单的解决方案是使用if语句。

if (myCond) arr.push(element);

还有过滤器,但我不认为这是你在这里想要的,因为你似乎要“添加这个东西,如果这个条件是真的”,而不是根据某些条件检查所有东西。虽然,如果你想变得非常怪异,你可以这样做(不建议,但你可以这样做很酷)。

var arr = ["a", cond && "bar"];
arr.filter( e => e)

基本上它会过滤掉所有非真值。

const cond = false;
const myArr = ["foo", cond ? "bar" : null].filter(Boolean);

console.log(myArr)

将导致["foo"]

你可以试试简单的if:

if(cond) {
    myArr.push("bar");
}

有条件地添加元素

/**
 * Add item to array conditionally.
 * @param {boolean} condition
 * @param {*} value new item or array of new items
 * @param {boolean} multiple use value as array of new items (for future)
 * @returns {array} array to spread
 * @example [ ...arrayAddConditionally(true, 'foo'), ...arrayAddConditionally(false, 'bar'), ...arrayAddConditionally(true, [1, 2, 3]), ...arrayAddConditionally(true, [4, 5, 6], true) ] // ['foo', [1, 2, 3], 4, 5, 6]
 */
export const arrayAddConditionally = (condition, value, multiple) => (
    condition
        ? multiple ? value : [value]
        : []
);

创建带有条件元素的数组


/**
 * Create array with conditional elements
 * @typedef {[condition: boolean, value: any, multiple: boolean]} ConditionalElement
 * @param {(ConditionalElement|*)[]} map non-array element will be added as it is, array element must allways be conditional
 * @returns {array} new array
 * @example createArrayConditionally([[true, 'foo'], [false, 'baz'], [true, [1, 2, 3]], [true, [4, 5, 6], true], {}]) // ['foo', [1,2,3], 4, 5, 6, {}]
 */
export const createArrayConditionally = (map) => (
    map.reduce((newArray, item) => {
        // add non-conditional as it is
        if (!Array.isArray(item)) {
            newArray.push(item);
        } else {
            const [condition, value, multiple] = item;
            // if multiple use value as array of new items
            if (condition) newArray.push[multiple ? 'apply' : 'call'](newArray, value);
        }
        return newArray;
    }, [])
);