美文网首页
JavaScript - 类数组对象与数组

JavaScript - 类数组对象与数组

作者: ElricTang | 来源:发表于2019-10-20 15:34 被阅读0次

类数组对象

  • 有length属性
  • 属性名为正整数(对应于数组的索引)
  • 没有数组的方法

例子:

  1. arguments
function arrayLike(){
    console.log(arguments);
    console.log(arguments.length);
}
arrayLike(1,2,3,4,5);
// [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
// 5
  1. DOM API(document.getElementsByTagName()等)
var a = document.getElementsByTagName('div');
Array.isArray(a);// false

如何将类数组对象转换为数组?

  1. Array.prototype.slice.call()
function arrayLike(){
    let res = Array.prototype.slice.call(arguments);
    console.log(res);
    console.log(Array.isArray(res));
}
arrayLike(1,2,3,4,5);
// [ 1, 2, 3, 4, 5 ]
// true
  1. Array.from()
function arrayLike(){
    let res = Array.from(arguments);
    console.log(res);
    console.log(Array.isArray(res));
}
arrayLike(1,2,3,4,5);
// [ 1, 2, 3, 4, 5 ]
// true
  1. 扩展运算符(...),针对有iterator接口的类数组对象
function arrayLike(){
    let res = [...arguments];
    console.log(res);
    console.log(Array.isArray(res));
}
arrayLike(1,2,3,4,5);
// [ 1, 2, 3, 4, 5 ]
// true

相关文章

网友评论

      本文标题:JavaScript - 类数组对象与数组

      本文链接:https://www.haomeiwen.com/subject/dqnwmctx.html