JavaScript 数组是如何实现的? [英] How are JavaScript arrays implemented?

查看:32
本文介绍了JavaScript 数组是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也就是下面的代码是怎么做的:

Namely, how does the following code:

var sup = new Array(5);
sup[0] = 'z3ero';
sup[1] = 'o3ne';
sup[4] = 'f3our';
document.write(sup.length + "<br />");

输出'5'作为长度,当你所做的只是设置各种元素?

output '5' for the length, when all you've done is set various elements?

我对这段代码的问题"是我不明白 length 如何在不调用 getLength()setLength() 的情况下改变代码>方法.当我执行以下任何操作时:

My 'problem' with this code is that I don't understand how length changes without calling a getLength() or a setLength() method. When I do any of the following:

a.length
a['length']
a.length = 4
a['length'] = 5

在非数组对象上,它的行为类似于字典/关联数组.当我对数组对象执行此操作时,它具有特殊含义.JavaScript 中的什么机制允许这种情况发生?JavaScript 是否有某种类型的属性系统可以翻译

on a non-array object, it behaves like a dict / associative array. When I do this on the array object, it has special meaning. What mechanism in JavaScript allows this to happen? Does JavaScript have some type of property system which translates

a.length
a['length']

进入获取"方法和

a.length = 4
a['length'] = 5

进入设置"方法?

推荐答案

JavaScript 中的一切都是对象.对于 Arraylength 属性返回数组索引项的内部存储区域的大小.由于 [] 运算符适用于数字和字符串参数,可能会引起一些混淆.对于数组,如果将它与数字索引一起使用,它会返回/设置预期的索引项.如果将它与字符串一起使用,它会返回/设置数组对象上的命名属性 - 除非字符串对应于数值,否则它会返回索引项.这是因为在 JavaScript 中,数组索引被隐式的 toString() 调用强制转换为字符串.坦率地说,这只是让你挠头说JavaScript,这,这就是他们嘲笑你的原因"的又一件事.

Everything in JavaScript is an object. In the case of an Array, the length property returns the size of the internal storage area for indexed items of the array. Some of the confusion may come into play in that the [] operator works for both numeric and string arguments. For an array, if you use it with a numeric index, it returns/sets the expected indexed item. If you use it with a string, it returns/sets the named property on the array object - unless the string corresponds to a numeric value, then it returns the indexed item. This is because in JavaScript array indexes are coerced to strings by an implicit toString() call. Frankly, this is just one more of those things that makes you scratch your head and say "JavaScript, this, this is why they laugh at you."

实际的底层表示可能因浏览器而异(也可能不会).除了使用它时提供的接口之外,我不会依赖任何其他东西.

The actual underlying representation may differ between browsers (or it may not). I wouldn't rely on anything other than the interface that is supplied when working with it.

您可以在 了解更多关于 JavaScript 数组的信息MDN.

这篇关于JavaScript 数组是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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