[英]Why does a function, that returns Function.prototype.call() acts differently here?
> Array.prototype.slice.call('1, 2, 3');
// returns: [ '1', ',', ' ', '2', ',', ' ', '3' ]
但:
> function toArray() {
... return Array.prototype.slice.call(arguments);
... };
> let some = toArray('1, 2, 3');
> some // returns [ '1, 2, 3' ]
這是為什么? 作為參數傳遞的是同一件事,但是結果不同。
arguments != '1, 2, 3'
。
arguments
是一個包含所有參數的類似數組的對象,它不是第一個參數。
return Array.prototype.slice.call(arguments[0]);
…將是等效的。
在第一個示例中,使用傳遞為參數的字符串來調用slice
。 這樣,它被視為字符數組。 因為沒有提供slice的起始位置,所以將返回整個數組。 在第二個示例中,使用arguments
對象調用slice
,該對象是類似數組的結構。 因此,您具有在索引0上具有字符串的array(-like)。因為同樣,您沒有提供起始索引,所以將返回包含一項的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.