美文网首页
JS基础 - 伪数组arguments

JS基础 - 伪数组arguments

作者: SY | 来源:发表于2021-11-24 19:22 被阅读0次

何为伪数组

伪数组有两个特点:

  1. 具有length属性,其他属性(索引)为非负整数
  2. 但是却不具备数组的方法
    也就是看起来像是数组,然而并不是…

举个例子看看

  1. 函数内部的arguments
function testArguments(a, b, c) {
    console.log(`arguments is array: ${Array.isArray(arguments)}`);
    console.log(arguments[0]);
    console.log(arguments[1]);
    console.log(arguments[2]);
}
testArguments(1,2,3);
image.png
如何判断真伪数组
使用instanceof 方法
使用Array.isArray()方法: 未必准确,见下文, 使用伪数组.proto = Array.prototype;转换后不可用。
伪数组.constructor === Array; 适用于带constructor的场景
Object.prototype.toString.call(arr) === ‘[object Array]’
尝试一下:
function testArguments(a, b, c) {
    console.log(`arguments is array: ${Array.isArray(arguments)}`);
    console.log(`arguments is array: ${arguments instanceof Array}`);
    console.log(`arguments is object: ${arguments instanceof Object}`);

    const newArguments = Array.prototype.slice.call(arguments);
    console.log(`newArguments is array: ${Array.isArray(newArguments)}`);
    console.log(`newArguments is array: ${newArguments instanceof Array}`);
    console.log(`newArguments is object: ${newArguments instanceof Object}`);
}

testArguments(1,2,3);
image.png

[图片上传中...(image.png-58e6ee-1637663233310-0)]

如何把伪数组转换成数组
Array.prototype.slice.call(); / Array.prototype.slice.apply();
原型继承: 伪数组.proto = Array.prototype;arguments 无影响正常使用
ES6中数组的新方法 from()
方法一: Array.prototype.slice.call(); / Array.prototype.slice.apply();

function testArguments(a, b, c) {
    console.log(`arguments is array: ${Array.isArray(arguments)}`);
    console.log(`arguments is array: ${arguments instanceof Array}`);

    const newArguments = Array.from(arguments);
    console.log(`newArguments is array: ${Array.isArray(newArguments)}`);
    console.log(`newArguments is array: ${newArguments instanceof Array}`);
}
testArguments(1,2,3);
image.png

相关文章

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

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

  • JS基础 - 伪数组arguments

    何为伪数组 伪数组有两个特点: 具有length属性,其他属性(索引)为非负整数 但是却不具备数组的方法也就是看起...

  • 2018-04-22

    javascript基础 一.函数的arguments 伪数组:像数组,但不是数组 可以动态添加参数 二.函数的其...

  • arguments小笔记

    为什么说arguments是伪(类)数组?答:因为arguments它不是数组,却用起来像数组,有length属性...

  • 关于伪数组

    关于伪数组 常见的伪数组都有哪些?arguments、通过document.getElements..获取到的内容...

  • 伪数组转数组实现方式

    伪数组转数组方法 伪数组也叫类数组。像函数中的arguments(箭头函数除外)或者 一组元素返回的集合。 有时操...

  • js中的arguments及其callee属性

    arguments 在js的函数内,可以通过arguments来访问参数数组,第一个元素为arguments[0]...

  • JavaScript函数和对象

    函数、对象 一. 目标 使用arguments获取函数的所有参数 arguments是一个伪数组,可以暂且作为一个...

  • ES6学习(5)

    设置函数参数的默认值 rest参数:用来获取函数的实参,用于代替arguments,arguments是一个伪数组...

  • JS基础数组与伪数组

    1.基本用法 window.Array是全局函数(也是函数) Array()与new Array()是一样的效果在...

网友评论

      本文标题:JS基础 - 伪数组arguments

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