js如何创建函数

JavaScript018

js如何创建函数,第1张

JS中创建函数的几种方法

声明函数:最普通最标准的声明函数方法,包括函数名及函数体。

function fn1(){}

创建匿名函数表达式:创建一个变量,这个变量的内容为一个函数

var fn1 = funciton (){}

创建具名函数表达式:具名函数表达式的函数名只能在创建函数内部使用,即采用此种方法创建的函数在函数外层只能使用fn1不能使用func_name的函数名。func_name的命名只能在创建的函数的内部使用

var fn1 = funciton func_name(){}

自执行函数:自执行函数属于上述的“函数表达式”,规则相同

(function(){alert(1)})()

(function fn1(){alert(1)})()

Function构造函数

可以给 Function 构造函数传一个函数字符串,返回包含这个字符串命令的函数,此种方法创建的是匿名函数。

其他创建函数的方法

当然还有其他创建函数或执行函数的方法,这里不再多说,比如采用 eval , setTimeout , setInterval 等非常用方法,这里不做过多介绍,属于非标准方法,这里不做过多展开

JS中Math函数的常用方法

Math是数学函数,但又属于对象数据类型typeof Math=>‘object’

console.dir(Math)查看Math的所有函数方法。

1,Math.abs()获取绝对值

Math.abs(-12) = 12

2,Math.ceil() and Math.floor()向上取整和向下取整

console.log(Math.ceil(12.03))//13

console.log(Math.ceil(12.92))//13

console.log(Math.floor(12.3))//12

console.log(Math.floor(12.9))//12

3,Math.round()四舍五入

注意:正数时,包含5是向上取整,负数时包含5是向下取整。

1、Math.round(-16.3) = -16

2、Math.round(-16.5) = -16

3、Math.round(-16.51) = -17

4,Math.random()取[0,1)的随机小数

案例1:获取[0,10]的随机整数

console.log(parseInt(Math.random()*10))//未包含10

console.log(parseInt(Math.random()*10+1))//包含10

案例2:获取[n,m]之间的随机整数

Math.round(Math.random()*(m-n)+n)

5,Math.max() and Max.min()获取一组数据中的最大值和最小值

console.log(Math.max(10,1,9,100,200,45,78))

console.log(Math.min(10,1,9,100,200,45,78))

6,Math.PI获取圆周率π 的值

console.log(Math.PI)

7,Math.pow() and Math.sqrt()

Math.pow()获取一个值的多少次幂

Math.sqrt()对数值开方

Math.pow(10,2) = 100

Math.sqrt(100) = 10