JavaScript - 数组和类数组对象之间的区别 [英] JavaScript - Difference between Array and Array-like object

查看:24
本文介绍了JavaScript - 数组和类数组对象之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JavaScript 中经常遇到术语类数组对象".它是什么?它和普通数组有什么区别?类数组对象和普通对象有什么区别?

解决方案

这是什么?

一个对象,它具有一个非负Integerlength属性,通常还有一些索引属性.例如

var ao1 = {length: 0},//像 []ao2 = {0: 'foo', 5: 'bar', length: 6};//像 ["foo", undefined × 4, "bar"]

您可以使用Array.prototype.slice

类数组对象转换为它们的数组对应对象

var arr = Array.prototype.slice.call(ao1);//[]

<块引用>

它和普通数组有什么区别?

它不是由 Array 构造的,也不是用 Array 文字 [] 构造的,因此(通常)不会从​​ 继承Array.prototype.length 属性通常也不会自动更新.

ao1 instanceof Array;//错误的ao1[0] = 'foo';ao1.length;//0,没有自动更新

<块引用>

类数组对象和普通对象有什么区别?

没有区别.甚至普通的数组JavaScript

中也是对象

ao1 instanceof Object;//真的[] 对象的实例;//真的

I have been coming across the term "Array-Like Object" a lot in JavaScript. What is it? What's the difference between it and a normal array? What's the difference between an array-like object and a normal object ?

解决方案

What is it?

An Object which has a length property of a non-negative Integer, and usually some indexed properties. For example

var ao1 = {length: 0},                     // like []
    ao2 = {0: 'foo', 5: 'bar', length: 6}; // like ["foo", undefined × 4, "bar"]

You can convert Array-like Objects to their Array counterparts using Array.prototype.slice

var arr = Array.prototype.slice.call(ao1); // []

Whats the difference between it and a normal array?

It's not constructed by Array or with an Array literal [], and so (usually) won't inherit from Array.prototype. The length property will not usually automatically update either.

ao1 instanceof Array; // false
ao1[0] = 'foo';
ao1.length; // 0, did not update automatically

Whats the difference between an array-like object and a normal object?

There is no difference. Even normal Arrays are Objects in JavaScript

ao1 instanceof Object; // true
[] instanceof Object; // true

这篇关于JavaScript - 数组和类数组对象之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆