美文网首页前端攻城狮
JS:什么是伪数组

JS:什么是伪数组

作者: limengzhe | 来源:发表于2021-02-02 14:43 被阅读0次

什么是伪数组?

伪数组,即 arrayLike,也称为类数组。是一种按照索引存储数据且具有 length 属性的对象。因为是对象,所以不能调用数组的方法,比如 forEach()push() 等。

下面的 a 对象就是一个伪数组:

let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

常见的伪数组有哪些?

  • 函数中的 arguments
test(1, 2, 3, 4);

function test() {
  console.log(arguments); // expected output: [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }
  console.log(arguments.length); // expected output: 4
}
  • document.querySelectorAll() 等批量选择元素的方法的返回值
const elements = document.querySelectorAll("div");
console.log(elements); // expected output: NodeList(4) [div, div, div, div]
  • <input/> 文件上传后的 files
<html>
  <body>
    <input type="file" name="file" id="input" onchange="fileChange()" />
  </body>
  <script>
    // 选择文件后触发
    function fileChange() {
      console.log(document.querySelector("#input").files); // expeced output: FileList {0: File, length: 1}
    }
  </script>
</html>

如何将伪数组转换为数组?

  • ES2015 新增的 Array.from() 方法
let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = Array.from(a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]
  • 数组的 slice() 方法
let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = [].slice.call(a);
let c = [].slice.apply(a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]
console.log(c); // expected output: [ 'x', 'y', 'z' ]
  • 数组的 concat() 方法
let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = [].concat.apply([], a);
console.log(b); // expected output: [ 'x', 'y', 'z' ]
  • 遍历伪数组的每一项,将其添加到一个新的数组
let a = {
  0: "x",
  1: "y",
  2: "z",
  length: 3,
};

let b = [];
for (let i = 0; i < a.length; i++) {
  b.push(a[i]);
}
console.log(b); // expected output: [ 'x', 'y', 'z' ]

相关文章

  • JS:什么是伪数组

    什么是伪数组 伪数组,即 arrayLike,也称为类数组。是一种按照索引存储数据且具有 length 属性的对象...

  • 关于javascript中的伪数组

    1、什么是js伪数组? 请看下面一段代码: 控制台输出: 上图就是一个伪数组,长相很像数组,但是将他的原型 _pr...

  • JS 将伪数组转换成数组 🎄

    本文简介 点赞 + 关注 + 收藏 = 学会了 在 JS 中,伪数组 是非常常见的,它也叫 类数组。伪数组可能会给...

  • JS 将伪数组转换成数组

    本文简介 点赞 + 关注 + 收藏 = 学会了 在 JS 中,伪数组 是非常常见的,它也叫 类数组。伪数组可能会给...

  • 2019前端经典面试题

    1.简述对标签语义化的理解。 2. css实现垂直水平居中 3. js中哪些是伪数组?如何将伪数组转化为标准数组?...

  • call,apply,bind的实际应用

    call,apply,bind详解传送门 求数组中的最大和最小值 将伪数组转化为数组 js中的伪数组(例如通过do...

  • js伪数组

    伪数组是一个含有length属性的json对象,它是按照索引的方式存储数据,它并不具有数组的一些方法. 1. 将伪...

  • $.each()与forEach()的区别,伪数组是什么

    $.each()是jq中的方法,forEach()是js方法1、$.each()可以遍历伪数组;forEach()...

  • javascript中的伪(类)数组

    1.什么是伪数组? 伪数组(ArrayLike)又称类数组,虽然从名字上来看,貌似和数组很像,但实际上和数组有很大...

  • Android 程序员搞 web 之 js基础(十)

    Android 程序员搞 js 之 基础(九) 一、arguments 对象伪数组 这个伪对象可以替换 函数传入的...

网友评论

    本文标题:JS:什么是伪数组

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