这对于 Lodash castArray 函数来说并没有什么特别之处。有没有什么方法可以在没有任何外部库的情况下使用最新的语言功能来解决这个任务,但仍然很快?
如果您不熟悉该任务:
castArray(['abc', 'def'])
// ['abc', 'def']
castArray('abc')
// ['abc']
castArray()
// []
castArray(undefined)
// [undefined]
有没有办法不用类型检查就可以做到这一点? 请注意,我寻找最短的等效项 ES6+。
您可以采用一个默认值为空数组的函数,并返回该数组或新数组的检查结果。
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
上面的答案没有考虑 NodeLists 和其他类似数组(Itrable)的对象。
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]
}
(检查可迭代性来自这里检查某些东西是否可迭代)
你总是可以做
[maybeArrayMaybeNot].flat()
。
const maybeArrayMaybeNot = /* ... */;
const definitelyArray = [maybeArrayMaybeNot].flat();
console.log([].flat());
//[]
console.log([[]].flat());
//[]
console.log([undefined].flat());
//[ undefined ]
console.log([[10, 20, 30]].flat());
//[ 10, 20, 30 ]
console.log([true].flat());
//[ true ]
console.log([[undefined]].flat());
//[ undefined ]
console.log(['string'].flat());
//[ 'string' ]
console.log([['string']].flat());
//[ 'string' ]
console.log([['string1', 'string2', 'string3']].flat());
//[ 'string1', 'string2', 'string3' ]