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

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

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

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


你可以试试简单的if:

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

除了使用push,你没有太多的选择:

const cond = true;
const myArr = ["foo"];

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

另一个想法是添加null并过滤掉它们:

const cond = true;
const myArr = ["foo", cond ? "bar" : null];

myArr = myArr.filter((item) => item !== null);

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

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 populate = function(...values) {
    return values.filter(function(el) {
        return el !== false
    });
};

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

返回

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

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


当条件为false时,可以将数组展开到数组内部,以保持项数组干净。

你可以这样做:

//返回['foo', 'bar'] Const项= [ “foo”, …真的吗?['bar']: [], …假的?['falsy']: [], ] console.log(物品)

解释:

如你所见,三元运算符总是返回一个数组。

如果条件为真,则返回['bar'],否则返回空数组[]。

之后我们散开……结果数组(来自三元操作)和数组的项被推入到父数组。

如果没有任何数组项(当三元检查为false时),则不会推送任何东西,这是我们的目标。


在另一个回答中,我解释了同样的想法,只是针对对象。你也可以在这里查看。


我会这样做

[
  true && 'one',
  false && 'two',
  1 === 1 && 'three',
  1 + 1 === 9 && 'four'
].filter(Boolean) // ['one', 'three']

注意,这也会删除错误的值,比如空字符串。


如果你正在使用es6,我会建议

Let array = [ “自行车”, “汽车”, Name === "van" ?"van": null, “公共汽车”, “卡车”, ] .filter(布尔);

如果name = "van",该数组将只包含值"van",否则将被丢弃。


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

console.log(myArr)

将导致["foo"]


有条件地添加元素

/**
 * 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;
    }, [])
);


这是Jordan Enev的答案的替代方案,如果你不太关心性能,感觉你想学习更多关于Javascript的知识:)

如果你想这样做,但是没有false/undefined/null元素

['foo', true && 'bar', null && 'baz']; // ['foo', 'bar', null]

你可以这样做:

['foo', true && 'bar', ...Object.values({ ...(null && ['baz']) })]; // ['foo', 'bar']

最后,正条件将如预期的那样工作:

['foo', true && 'bar', ...Object.values({ ...(true && ['baz']) })]; // ['foo', 'bar', 'baz']

好处:如果你想向数组中添加一个东西,但这个东西可能是假的,然后你不想让它在那里,不做第二次操作,这里有一种方法:

const foo = 1; // 1
const bar = (() => 'expensive result that turns out falsy for bar' && false)(); // false
const baz = (() => 'expensive result for baz')(); // 'expensive result'
const conditionalArrayWrapperFor = i => i ? [i] : [];
// tip: you can always inline conditionalWrapper if you only execute it once
// for instance, if you're using this inside a reduce call
[foo, ...conditionalArrayWrapperFor(bar), ...conditionalArrayWrapperFor(baz)] // [1, 'expensive result for baz']