对 js 稍有了解的朋友应该知道, js 里有一种叫做"类数组"的东西
如字面意思, 是一些类似数组的数据类型
为什么用"一些"呢?
因为类数组不是一种数据类型, 是好几种类型的统称, 如:NodeList, Set, Arguments 都是类数组
类数组有数组的一部分特性, 而不是全部特性, 如 Set 是没有 length 属性的
var set = new Set([1, 2, 3, 4])
console.log(set.length) // undefined
如果要把类数组当数组用, 那就需要将类数组转成数组类型
ES6 提供了简单好用的方法 Array.from() 和 扩展运算符
var set = new Set([1, 2, 3, 4])
console.log(Array.from(set))
console.log([...set])
就是这么简单, 下面看看其它类数组类型转数组的案例
// 输出值及值的类型
function consoleTypeof(params) {
console.log(params)
console.log(Object.prototype.toString.call(params))
}
var set = new Set([1, 2, 3, 4])
var _NodeList = document.querySelectorAll('div')
consoleTypeof(set)
consoleTypeof(Array.from(set))
consoleTypeof([...set])
consoleTypeof(_NodeList)
consoleTypeof(Array.from(_NodeList))
consoleTypeof([..._NodeList]);
(function () {
consoleTypeof(arguments)
consoleTypeof(Array.from(arguments))
consoleTypeof([...arguments])
})(1, 2, 3, 4, 5);
end