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

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

问题描述

也就是说,请问以下code:

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?

我的'问题'这个code是,我不知道如何长度更改,而不调用的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']

成get方法以及

into "get" methods and

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

进入设置的方法?

into "set" methods?

推荐答案

在JavaScript的一切都是对象。在阵列的情况下,长度属性返回内部存储区为数组的索引项的大小。有些混乱可能会进入,该 [] 运营商同时适用于数字和字符串参数的发挥。对于一个数组,如果你有一个数字索引使用它,它会返回/设置预期索引项。如果你用字符串使用它,它会返回/设置数组对象的命名属性 - 除非字符串对应一个数值,然后返回索引项。这是因为在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."

实际的基础再presentation可能浏览器之间(也可能不是或)有所不同。我不会依赖比与它一起工作时,提供的接口以外的任何其他。

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数组在<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\">MDN.

You can find out more about Javascript arrays at MDN.

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

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