【源码阅读】arrify|如何把一个值转换为一个数组?

87 阅读1分钟

1.转换数组的场景 (类数组转化为数组) 如 arguments转换为数组 原生js获取的DOM集合是一个类数组对象,所以不能直接利用数组的方法(例如:forEach,map等),需要转换为数组后,才能用数组的方法。

2.常见转换数组的方法

Array.from(likeList)
Array.prototype.slice.call(likeList)
解构赋值 […likeList]

3.arrify源码

export default function arrify(value){
	if(value===null||value===undefined){
		return[];
	}
	if(Array.isArray(value)){
		returnvalue;
	}
	if(typeofvalue==='string'){
		return[value];
	}
	if(typeofvalue[Symbol.iterator]==='function'){
		return[...value];
	}
	return[value];
}