判断数组
js
// 1.
[] instanceof Array;
// 2. 数组重写了toString()方法需要借用
Object.prototype.toString.call([]) === '[object Array]'
// 3.
Array.prototype.isPrototypeOf([]);
// 4.
[].constructor === Array;
// 5.
Array.isArray([]);
如何处理类数组对象
JavaScript类数组对象的定义
可以同过索引访问元素, 并且拥有length属性
没有数组的方法,例如 push, forEach, indexOf等
js
var foo = {
0: 'js',
1: 'Node',
2: 'TS',
length: 3
};
转换方式
js
// 1.
Array.prototype.slice.call(arguments);
Array.prototype.slice.apply(arguments);
[].slice.call(arguments)
// 2. 需要arguemnts必须有遍历接口
[...arguments]
// 3.
Array.from(arguemnts);
// 4.
[].concat.apply([], arguments)
// 5.
function toArray(s) {
var arr = [];
for(var i =0, len =s.length; i< len; i++>) {
arr[i] = s[i]
}
return arr;
}
注意
- 数组的长度由类数组的length决定
- 索引不连续,会自动补位undefined
- 仅仅考虑0和正整数索引
- slice会产生系数数组,内容是empty而不是undefined
- 类数组push注意,push操作是length所在的位置