您的位置:首页 > 其它

arguments和Array.prototype.slice.call(arguments,0);

2015-11-19 21:24 639 查看
下列错误的代码:原因是arguments并不是真正的数组。所以并不能直接用forEach来,可以把arguments转换成数组。
function useArguments() {
var sum = 0;

arguments.forEach(function(e){

sum+=e;

});

// for(var i=0;i<arguments.length;i++){

// sum=sum+arguments[i];

// }

return sum;

}

var s = useArguments(1, 2, 3, 4);
console.log(s);

或者改成
function useArguments() {

var sum = 0;

var args = Array.prototype.slice.call(arguments,0);

args.forEach(function(e){

sum+=e;

});

return sum;

}
var s = useArguments(1, 2, 3, 4);

题目描述

实现函数 callIt,调用之后满足如下条件

1、返回的结果为调用 fn 之后的结果

2、fn 的调用参数为 callIt 的第一个参数之后的全部参数

[b]输入例子:[/b]

var a = 1; var b = 2; var test = function (first, second) { return first === a && second === b;}; callIt(test, a, b);

function callIt(fn) {

var args = Array.prototype.slice.call(arguments,1);

var s = fn.apply(null,args);

return s;
}

function

callIt(fn) {

return

fn.apply(
this
,[].slice.call(arguments,1));

}


关于Array.prototype.slice.call(arguments,1);的解释

因为arguments并不是真正的数组对象,只是与数组类似而已,所以它并没有slice这个方法,

而Array.prototype.slice.call(arguments, 1)可以理解成是让arguments转换成一个数组对象,让arguments具有slice()方法。
要是直接写arguments.slice(1)会报错

Array.prototype.slice.call(arguments)能将具有length属性的对象转成数组;

var a={length:3,0:'abc',1:'def',2:'ghi'};

console.log(Array.prototype.slice.call(a));//  ["abc", "def",'ghi']

var a={length:0};

console.log(Array.prototype.slice.call(a));//  []

var a={length:3};

console.log(Array.prototype.slice.call(a));// [undefined, undefined, undefined]

Array.prototype.slice.call(arguments).slice(1)

在很多的例子里面都会看到以上的调用,开始看了很久也不明白是什么意思,最近研究了一下,终于明白了。
要讨论这样的调用方式,其实只有一个目的,
arguments (typeof arguments它是一个object ),而在这里调用的是array的slice 方法.
array.prototype.slice 是原型slice 方法,
call()查看帮助文档会发现,会把call(thisObject)做为当前上下文使用,(也可以简单thisObject可以调用Array的方法。)
slice()返回一个数组的一段

Array.prototype.slice.call(arguments,0);//将参数转换成真正的数组

call的作用是改变this的指向,就相当于arguments调用了,slice这个方法。0就是start=0,end没指定,所以返回整个arguments,这个时候就转换成数组了。
这里有一个问题

arguments.slice(0)//为什么不直接这样呢,非要用call改下this的指向就可以了?见下文的分析

引用: 能用slice方法的,只要有length属性就行。虽然arguments有length属性,但是没有slice方法,所以 呢,Array.prototype.slice()执行的时候,Array.prototype已经被call改成arguments了,因为满足 slice执行的条件(有length属性),所以没有报错。感觉有点hack的意思了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: