JS 类数组对象——Array-like Objects

本文介绍了JavaScript中的类数组对象,解释了其特性和用途,并通过实例展示了如何将其转换为标准数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是类数组对象?

类数组对象是JS里面比较常用的一个对象,平时在操作DOM或写function的时候经常会用到,虽然对初学者来说概念比较陌生。类数组对象具有数组对象的一些属性,比如length,可以遍历(for-in不可以)但是却不能使用数组对象的方法。
最常见的类数组就是function里面的参数变量arguments,通常传递给function的参数都会被存储在一个名为arguments的类数组里面。还比如获取DOM返回的结点列表(document.getElementsByTagName(), document.forms)也是一个类数组。

function takesTwoParams(a, b){
    console.log("you gave me "+arguments.length+" arguments");
    for(i=0; i<arguments.length; i++){
        console.log("parameter " + i + " = " + arguments[i]); 
    }
    console.log(" your parameters were " + arguments.join(", "));
}
takesTwoParams("one","two","three");
//输出:
//you gave me 3 arguments
//parameter 0 = one
//parameter 1 = two
//parameter 2 = three
//arguments.join is not a function

由上面的列子可以看出arguments是存储function实参的一个类数组,不具有Array的一些方法。那怎么样才能使用数组的方法呢?

类数组转换成数组

因为arguments也是一个数组,因此可通过Array的原型来实现。

function takesTwoParams(a, b){
    var args = Array.prototype.slice.call(arguments);
    console.log(" your parameters were " + args.join(","));
}
takesTwoParams("one","two","three");// your parameters were one,two,three

Array.prototype.slice.call(arguments)能将具有length属性的对象转成长度为length的数组,除了低版本IE下的节点集合(因为低版本ie下的dom对象是以com对象的形式实现的,js对象与com对象不能进行转换),如下:

//有length属性
var a={length:1,0:'first',1:'second'};
Array.prototype.slice.call(a);//["first"]

var a={length:3,0:'first',1:'second'};
Array.prototype.slice.call(a);//  ["first", "second", undefined]

var a={length:2};
Array.prototype.slice.call(a);//  [undefined, undefined] 

//没有length属性
var a={0:'first',1:'second'};
Array.prototype.slice.call(a);// []

由于IE不支持Array.prototype.slice.call,所以以下为兼容性写法:

function hybridToArray(nodes){
    try{
        // works in every browser except IE
        var arr = Array.prototype.slice.call(nodes);
        return arr;
    } catch(err){
        // slower, but works in IE
        var arr = [],
            length = nodes.length;
        for(var i=0; i<length; i++){
            arr.push(nodes[i]);
        }
        return arr;
    }
}
### JavaScript 中检测从服务器接收的数据类型 为了确保应用程序能够正确处理来自服务器的不同类型的响应,在接收到数据之后对其进行类型检查是非常重要的。以下是几种方法来验证所获得的内容是否符合预期。 #### 使用 `typeof` 运算符判断基本类型 对于简单的值比如字符串、数字或布尔值,可以利用内置的 `typeof` 关键字来进行初步分类: ```javascript fetch('/api/data') .then(response => response.json()) .then(data => { const typeOfData = typeof data; console.log(`The type of received data is ${typeOfData}`); if (typeOfData === 'string' || typeOfData === 'number' || typeOfData === 'boolean') { // Handle primitive types here } }) .catch(error => console.error('Error fetching or processing data:', error)); ``` #### 利用 Array.isArray 方法识别数组 当不确定返回的是单个对象还是多个项目的集合时,可以通过调用静态函数 `Array.isArray()` 来确认结果是不是一个数组实例: ```javascript if (Array.isArray(data)) { // Data is an array, handle accordingly. } else { // Not an array, proceed with other checks... } ``` #### instanceof 或 Object.prototype.toString.call 对象类型判定 针对更复杂的情况如日期时间戳或是自定义类的对象实例,则可借助于 `instanceof` 操作符或者是更为通用的方式——通过 `Object.prototype.toString.call()` 获取内部 [[Class]] 属性来进行精确匹配[^1]。 ```javascript // Using instanceof for custom classes or built-in objects like Date const dateInstanceCheck = data instanceof Date; // Or using toString call to get the exact class name even across frames/contexts const internalClassName = Object.prototype.toString.call(data); console.log(internalClassName); switch (internalClassName) { case '[object Object]': // Handle plain object cases break; case '[object Array]': // Already handled above but included as example break; default: // Other specific handling based on detected type } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值