JavaScript_5
函数function:
function sayHello(name){
alert("hello,"+name);
}
sayHello("Tom");//hello,Tom
function sayHello(name){
return "hello,"+name;
}
var msg=sayHello("Tom");
alert(msg);//hello,Tom
函数中的参数:
- JS中函数不介意传递的参数数量和数据类型
- 也就是说,定义了一个需要传递两个参数的函数你可以传递一个,两个,三个,甚至可以不传递
function sayHello(name,age){
alert(name+" is "+age+"岁。");
}
sayHello();//undefined is undefined岁。
sayHello("tom");//tom is undefined岁。
sayHello("tom",12);//tom is 12岁。
sayHello("tom",12,"jack")//tom is 12岁。
- 参数在JavaScript内部用一个名为arguments的类似数组的对象来管理
function sayHello(name,age){
alert(name+" is "+arguments[1]+"岁。");
alert(arguments.length);//2
}
sayHello("tom",12);//tom is 12岁。
function sayHello(name,age){
for(var temp in arguments){
alert(temp);//0 1
alert(arguments[temp]);//tom 12
}
}
sayHello("tom",12);