前几天关于arguments的学习笔记
var abc = function(){// can not invoke "abc"var result = (function(){})();}===== Chinese Version =====
var abc = function(){// 不能直接调用 "abc"var result = (function(){})();}
?
?
var sum = function(){ //建立一个匿名函数; var args = arguments; if(args.length !== 2){ return !1; //判断参数的length } var min = parseInt(args[0], 10), max = parseInt(args[1], 10); //赋值min,max,将第一个第二个参数转换为十进制,如果不是数 值将会返回NaN if(!isNaN(min) && !isNaN(max)){ if(min === max){ return min; } if(min > max){ max = [min, min = max][0]; //判断min,max大小,如果min大于max,交换min与max的值; } return min + args.callee.call(null, ++min, max); //循环,每次自身+1,并返回自身,直到max为止 } return !isNaN(min) ? min : max; };
?
关于
var min = parseInt(args[0], 10), max = parseInt(args[1], 10);
?
parseInt是将一个字符串转换成数值而如果
callee is a property of the arguments object. It can be used to refer to the currently executing function inside the function body of that function. This is for example useful when you don't know the name of this function, which is for example the case with anonymous functions.
下面是用callee来实现一个阶乘的函数:
?
function create() { return function(n) { if (n <= 1) return 1; return n * arguments.callee(n - 1); }; } var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1)
?
在这个函数中,在n<=1之前,参数都会被自身重复调用一次,当符合条件时,即最后n小于1只返回1执行。