首页 > IT职业 > IT图书 > JavaScript(二)之arguments详解
ECMAScript函数不介意传进来的参数个数和类型,
在函数体内可以通过arguments对象来访问这个参数数组
function hi(){
alert("hello"+arguments[0]+","+arguments[1]);
}
hi("kk","jun");// hellokk,jun function hi(name){
console.log(Array.isArray(arguments));// false
}
hi("name"); 将arguments类数组对象转换成数组:Array.prototype.slice.call(arguments);
function hi(name){
var args = Array.prototype.slice.call(arguments);
console.log(Array.isArray(args));// true
}
hi("name"); ES6新增实现:Array.from()
function hi(name){
var args = Array.from(arguments);
console.log(Array.isArray(args));// true
}
hi("name"); function hi(name){
console.log(arguments.length);
}
hi("name");//1
hi("name","age");//2 根据这个特性可以实现适当的功能,例如:
function add(){
if(arguments.length==1){
do something
}
if(arguments.length==2){
do something
}
} function hi(){
console.log(arguments[0]);
}
hi(); //undefined 有意思的题目 var sum = function(n) {
if(n == 1) {
return 1;
} else {
return n + arguments.callee(n-1);
//calllee,当函数被调用时,它的arguments.callee对象就会指向自身,也就是一个对自己的引用
}
}
console.log("sum =", sum(5)); function add() {
//console.log("length", arguments.length);
var len = arguments.length,
sum = 0;
for (var i = 0; i 来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2548/viewspace-2807740/ ,如需转载,请注明出处,否则将追究法律责任。