【问题标题】:How to avoid the castArray function?如何避免 castArray 函数?
【发布时间】:2019-07-24 10:52:18
【问题描述】:

Lodash castArray 函数没有什么特别之处。有没有什么方法可以在没有任何外部库的情况下使用最新的语言功能来解决此任务,但仍然很快?

如果您不熟悉该任务:

castArray(['abc', 'def'])
// ['abc', 'def']
castArray('abc')
// ['abc']
castArray()
// []
castArray(undefined)
// [undefined]

有没有办法在没有类型检查的情况下做到这一点? 请注意,我寻找的是最短的等价物,ES6+。

【问题讨论】:

  • 点击您发布的链接中的“来源”。
  • 改变了你的要求! “没有类型检查”使您的问题 相当 不同并使当前答案无效。那是not good。不过,castArray(undefined) // [undefined] 似乎很好 - 这是文档中已有的说明,但不需要注意。
  • 另外,如果没有类型检查,我不确定你如何解决这个问题。您需要为数组而不是数组做不同的事情。
  • 对不起,误会了,我还是想找个方便快捷的方法来做这件事。

标签: javascript arrays lodash


【解决方案1】:

您可以使用一个默认值为空数组的函数,并返回检查该数组或新数组的结果。

const castArray = (data = []) => Array.isArray(data) ? data : [data];

console.log(castArray(['abc', 'def']));  // ['abc', 'def']
console.log(castArray('abc'));           // ['abc']
console.log(castArray());                // []

console.log(castArray(1));               // => [1]
console.log(castArray({ 'a': 1 }));      // => [{ 'a': 1 }]
console.log(castArray('abc'));           // => ['abc']
console.log(castArray(null));            // => [null]
console.log(castArray(undefined));       // => [undefined]
console.log(castArray());                // => []

var array = [1, 2, 3];
console.log(castArray(array) === array); // => true

【讨论】:

  • 刚刚添加了页面中的示例以显示它与 Lodash 的性能相同。
  • 其实castArray(undefined) 不适用。没有注意到 - 在这种情况下,它会创建一个空数组。 OP 可以决定这是否可以接受,但修改起来相对容易。
【解决方案2】:

上面的答案没有考虑 NodeLists 和其他类似数组的(Iterable)对象。

对 castArray 的更准确答案是

function isIterable(value) {
       return Symbol.iterator in Object(value)
}

function getElementsAsArray(obj) {
    if (!obj) {
        return []
    }

    if (isIterable(obj) && typeof obj !== 'string') {
        return Array.from(obj)
    }

    return [obj]
}

(检查可迭代是从这里Checking whether something is iterable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 2018-08-05
    • 2019-08-12
    • 1970-01-01
    相关资源
    最近更新 更多