JavaScript 类数组对象代码举例
a = "hello"
[].map.call(a, (e) -> e.toUpperCase()) # => [ 'H', 'E', 'L', 'L', 'O' ]
[].reduceRight.call(a, (acc, e) -> acc + e) # => 'olleh'
b = {1: "a", 2: "b", 4: "c", length: 6}
[].reduce.call(b, (acc, e) -> acc + e) # => 'abc'
So what exactly makes an object “array-like”? The basic contract of
an array object amounts to two simple rules.codego.net for example.
一个数组对象相当于两个简单的规则
It has an integer length property in the range 0...2^32 – 1.
The length property is greater than the largest index of the object.
长度大于最大的索引对象。
n index is an integer in the range 0...2^32 – 2 whose string representation
is the key of a property of the object.
所以为什么 arguments, 字符串,和上面那个 b 对象可以看作类数组对象呢?
它们都有一个合法的 length 属性(0 到 2**32 - 1 之间的正整数)。
length 属性的值大于它们的最大索引(index)。
再举个例子:
b = {1: "a", 2: "b", 4: "c", length: 3}
[].reduce.call(b, (acc, e) -> acc + e) # => 'ab'
最大索引值是4要比 length 属性大了。所以表现的不正常了。只是定义了一个接口,只要符合这个接口,就可以利用数组的所有方法。
其实不是可以利用所有方法,Array.prototype.concat
是不能用的,因为它是把两个数组连接起来,你不是数组肯定是没法用它的。
字符串创建以后是不可变的(immutable),所以你怎么折腾它都是不可变的。
这段类数组对象用处还挺广泛的.
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30191680/viewspace-1546234/
,如需转载,请注明出处,否则将追究法律责任。