html中定义函数调⽤函数,请问HTMLfunction函数怎么定义和
调⽤?
/*javascript定义函数(声明函数)可以有三种⽅法:正常⽅法、构造函数、函数直接量。*/
/*1.正常⽅法 function(param){}*/
function print(msg)
{
document.write(msg,"");
}
/*如果函数不包含return 语句,只执⾏函数体内语句,并返回undefined*/
/*2.构造函数⽅法:new Function()*/
var add1=new Function('a','b','return a+b');
/
*3.函数直接量法,创建未命名函数,*/
var result = function(x,y){return x+y;};
/*也可以指定函数名*/
var result2 = function fact(x){if(x<1) return 1;else return x*fact(x-1)};
document.write('调⽤⼀般的⽅法:');
print("
");
print('调⽤构造函数⽅法:add1(5,6)');
print(add1(5,6));
print("
");
html如何下载print("调⽤函数直接量法:result(3,4)");
var re =result(3,4);
print(re);
print("调⽤函数直接量法:result2(3)");
print(result2(3));
print("
");
print('函数作为数据使⽤');
/*函数可以作为数据使⽤*/
function add(x,y){return x+y;}
function subtract(x,y){return x-y;}
function multiply(x,y){return x*y;}
function divide(x,y){return x/y;}
function operate(operator,operand1,operand2)
{
return operator(operand1,operand2);
}
//计算(2+3) + (4*5)
var i = operate(add,operate(add,2,3),operate(multiply,4,5)); print('(2+3) + (4*5)='+i);
print("
");
//使⽤函数直接量
var operators = new Object();
operators['add'] = function(x,y){return x+y;}
operators['substract'] = function(x,y){return x-y;}
operators['multiply'] = function(x,y){return x*y;}
operators['divide'] = function(x,y){return x/y;}
operators['pow'] = Math.pow;
function operate2(op_name,operand1,operand2)
{
if(operators[op_name] == null) return "unknown operator"; else return operators[op_name](operand1,operand2);
}
//定义"hello" + "" + "world"
var j = operate2("add","hello",operate2("add"," ","world")); var k = operate2("pow",10,2);
print(j);
print(k);
print("
");

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。