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

下列错误的代码:原因是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 的 第一个参数之后的全部参数
输入例子:
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()返回一个数组的一段

  1. Array.prototype.slice.call(arguments,0);//将参数转换成真正的数组  
call的作用是改变this的指向,就相当于arguments调用了,slice这个方法。0就是start=0,end没指定,所以返回整个arguments,这个时候就转换成数组了。
这里有一个问题
  1. arguments.slice(0)//为什么不直接这样呢,非要用call改下this的指向就可以了?见下文的分析  
引用: 能用slice方法的,只要有length属性就行。虽然arguments有length属性,但是没有slice方法,所以 呢,Array.prototype.slice()执行的时候,Array.prototype已经被call改成arguments了,因为满足 slice执行的条件(有length属性),所以没有报错。感觉有点hack的意思了。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值