Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

javascript - Array.prototype.slice.call()如何工作?(how does Array.prototype.slice.call() work?)

我知道它用于使参数成为一个真正的数组,但我不明白使用Array.prototype.slice.call(arguments)时会发生什么

  ask by ilyo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What happens under the hood is that when .slice() is called normally, this is an Array, and then it just iterates over that Array, and does its work.(在.slice()发生的事情是,当正常调用.slice()时, this是一个数组,然后它只是遍历该数组,并完成它的工作。)

How is this in the .slice() function an Array?(.slice()函数中的this怎么样?) Because when you do:(因为当你这样做时:) object.method(); ...the object automatically becomes the value of this in the method() .(...的object自动成为的值thismethod()) So with:(所以:) [1,2,3].slice() ...the [1,2,3] Array is set as the value of this in .slice() .(... [1,2,3]数组在.slice()设置为this的值。) But what if you could substitute something else as the this value?(但是,如果你可以用其他东西代替this值呢?) As long as whatever you substitute has a numeric .length property, and a bunch of properties that are numeric indices, it should work.(只要你替换的任何东西都有一个数字.length属性,以及一堆属性为数字索引,它应该有效。) This type of object is often called an array-like object .(这种类型的对象通常称为类似数组的对象 。) The .call() and .apply() methods let you manually set the value of this in a function.(.apply() .call().apply()方法允许您在函数中手动设置this的值。) So if we set the value of this in .slice() to an array-like object , .slice() will just assume it's working with an Array, and will do its thing.(因此,如果我们的值设置this.slice()到一个数组类的对象.slice()将只是假设它的工作与Array,并会做它的东西。) Take this plain object as an example.(以此普通对象为例。) var my_object = { '0': 'zero', '1': 'one', '2': 'two', '3': 'three', '4': 'four', length: 5 }; This is obviously not an Array, but if you can set it as the this value of .slice() , then it will just work, because it looks enough like an Array for .slice() to work properly.(这显然不是一个数组,但是如果你可以将它设置为.slice()this值,那么它就可以正常工作,因为它看起来就像一个数组,可以正常工作.slice() 。) var sliced = Array.prototype.slice.call( my_object, 3 ); Example: http://jsfiddle.net/wSvkv/(示例: http //jsfiddle.net/wSvkv/) As you can see in the console, the result is what we expect:(正如您在控制台中看到的,结果是我们所期望的:) ['three','four']; So this is what happens when you set an arguments object as the this value of .slice() .(所以当你将一个arguments对象设置为.slice()this值时会发生这种情况。) Because arguments has a .length property and a bunch of numeric indices, .slice() just goes about its work as if it were working on a real Array.(因为arguments有一个.length属性和一堆数字索引, .slice()就像它在一个真正的数组上工作一样。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...