【若川视野 x 源码共读】第33期 | arrify转数组
本文参加了由公众号@若川视野 发起的每周源码共读活动,点击了解详情一起参与。
本篇是源码共读第33期 | arrify转数组,点击了解本期详情
arrify
-
arrify是将传入数据结构转为数据结构
-
源码
export const arrify = (value) => {
if (value === null || typeof value === 'undefined') {
return [];
}
if (Array.isArray(value)) {
return value;
}
// String数据类型含有Iterator接口判断时得在typeof value[Symbol.iterator] === 'function'前否则会被结构
// arrify('123') ---> ['1', '2', '3']
if (typeof value === 'string') {
return [value];
}
// const arr = ['lucy', 'judy', 'mike'];
// const indexMap = new Map(arr.map((k ,v) => [k,v]));
// 含有Iterator接口的数据结构 value[Symbol.iterator]类型为function
if (typeof value[Symbol.iterator] === 'function') {
return [...value];
}
return [value];
}
3.测试
console.log(arrify(null)); ---> []
console.log(arrify([1, 2, 3])); ---> [1, 2, 3]
console.log(arrify('hello')); ---> ['h', 'e', 'l', 'l', 'o']
console.log(arrify(new Map(['h', 'i'].map((k ,v) => [k,v])))); ---> [[ "h", 0 ], [ "i",1 ]]
console.log(arrify({'t': 'p'})); ---> [{t: 'p'}]
Symbol类型学习
Symbol不属于unll,undefined,string,boolean,function,number,array,object其中一种
声明Symbol类型方式:
const symbol1 = Symbol(); // 可传字符串参数作文Symbol类型的标识以供辨别区分(对Symbol的描述);
const symbol2 = Symbol('lucy');
const object = {
[Symbol]: 'sym'
} // 可作为对象的唯一键名
console.log(symbol1); ---> 'Symbol()'
console.log(symbol2); ---> 'Symbol(lucy)'
console.log(object[Symbol]); ---> 'sym'
注意声明Symbol时不能使用new关键字
Symbol类型只能转换为Boolean或者String类型,不能与其他类型计算
Iterator学习
Iterator可理解为一种遍历器,是一种访问数据结构的机制
Array,String,Map,Set,函数入参argument对象,ListNode数据类型具备Iterator接口
ES6中创造了一种新的访问机制for...of主要提供给含有Iterator接口的数据结构
Iterator类型
interface IteratorResult {
value: any;
done: boolean;
}
iterface Iterator {
next: (value? any) => IteratorResult;
}
iterface Iterable {
[Symbol.Iterator](): Iterator;
}
如接口类型可见,Iterator接口部署在Symbol类型下
当调用类型下的Symbol.Iterator()函数时会返回一个还有next属性的函数,该函数返回一个对象{value, done}
每次调用next()则会返回下一个value&done值,迭代到最后value = undefined, done = true
const arr = ['1', '2', '3'];
const testCase = arr[Symbol.Iterator]();
testCase.next(); ---> {value: '1', done: false, };
testCase.next(); ---> {value: '2', done: false, };
testCase.next(); ---> {value: '3', done: false, };
testCase.next(); ---> {value: undefined, done: true, };
Iterator使用场景:es6中扩展运算符,解构赋值,yield
总结
通过学习本章源码,学习了Iterator,Symbol,巩固了es6的知识。
继续加油!!!