Array.slice和阵列之间的差异()。片 [英] Difference between Array.slice and Array().slice

查看:121
本文介绍了Array.slice和阵列之间的差异()。片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要通过约翰Resig的优秀 JavaScript高级教程我也没有搞明白什么是以下之间的差异来电:(请注意,论据是一个内置的JavaScript词,不正是一个数组因此与Array.slice黑客,而不是简单地调用arguments.slice)

I am going through John Resig's excellent Advanced javascript tutorial and I do not thoroughly understand what's the difference between the following calls: (please note that 'arguments' is a builtin javascript word and is not exactly an array hence the hacking with the Array.slice instead of simply calling arguments.slice)

>>> arguments  
[3, 1, 2, 3]  
>>> Array.slice.call( arguments )  
3,1,2,3 0=3 1=1 2=2 3=3  
>>> Array.slice.call( arguments, 1 )  
[]
>>> Array().slice.call( arguments )  
3,1,2,3 0=3 1=1 2=2 3=3  
>>> Array().slice.call( arguments, 1 )  
1,2,3 0=1 1=2 2=3

基本上我的误解归结为Array.slice和Array()。片之间的差别。究竟什么是这两个,为什么不Array.slice.call像预期的那样有什么区别? (这是回馈所有,但参数列表的第一个元素)

Basically my misunderstanding boils down to the difference between Array.slice and Array().slice. What exactly is the difference between these two and why does not Array.slice.call behave as expected? (which is giving back all but the first element of the arguments list).

推荐答案

不完全是。

看,当你调用String.substring.call(富,1)和字符串()substring.call(富,2)会发生什么:

Watch what happens when you call String.substring.call("foo", 1) and String().substring.call("foo", 2):

>>> String.substring.call("foo", 1)
"1"

>>> String().substring.call("foo", 1)
"oo"

Array.slice是<青霉>既不的正确引用附连到阵列原型也不(如Array()或[])连接到任何实例化的阵列实例的切片功能切片功能

Array.slice is neither properly referencing the slice function attached to the Array prototype nor the slice function attached to any instantiated Array instance (such as Array() or []).

事实上,Array.slice甚至非空在所有是一个不正确的实施对象(/功能/构造函数)的本身。 尝试运行在IE,相当于code,你会得到一个错误,Array.slice为空

The fact that Array.slice is even non-null at all is an incorrect implementation of the object (/function/constructor) itself. Try running the equivalent code in IE and you'll get an error that Array.slice is null.

这就是为什么Array.slice不正确的行为(也没有String.substring)。

This is why Array.slice does not behave correctly (nor does String.substring).

证明(以下东西应该永远不要指望基于切片(定义)...就像上面串()):

Proof (the following is something one should never expect based on the definition of slice()...just like substring() above):

>>> Array.slice.call([1,2], [3,4])
3,4

现在,如果你正确地调用或者实例化对象切片()的的数组原型,你会得到你所期望的:

Now, if you properly call slice() on either an instantiated object or the Array prototype, you'll get what you expect:

>>> Array.prototype.slice.call([4,5], 1)
[5]
>>> Array().slice.call([4,5], 1)
[5]

更多的证据...

More proof...

>>> Array.prototype.slice == Array().slice
true
>>> Array.slice == Array().slice
false

这篇关于Array.slice和阵列之间的差异()。片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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