使用示例
arrify可以将任何值转换为数组
import arrify from 'arrify';
arrify('🦄');
//=> ['🦄']
arrify(['🦄']);
//=> ['🦄']
arrify(new Set(['🦄']));
//=> ['🦄']
arrify(null);
//=> []
arrify(undefined);
//=> []
源码
export default function arrify (value) {
// null 和 undefined 直接返回 []
if (value === null || value === undefined) {
return []
}
// 数组原样返回 [1] => [1]
if (Array.isArray(value)) {
return value
}
// 字符类型 '1' => ['1']
if (typeof value === 'string') {
return [value]
}
// iterator new Set([1, 2]) => [1, 2]
if (typeof value[Symbol.iterator] === 'function') {
return [...value]
}
// 1 => [1]
// true => [true]
// {age:1} => [{age:1}]
// function(){} => [ƒ()]
return [value]
}
关于iterator
一些内置类型拥有默认的迭代器行为,其他类型(如 Object)则没有。下表中的内置类型拥有默认的@@iterator方法:
- Array.prototype@@iterator
- TypedArray.prototype@@iterator
- String.prototype@@iterator
- Map.prototype@@iterator
- Set.prototype@@iterator