码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript 函数

时间:2018-06-15 15:51:04      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:使用   就是   函数名   数组   java   IV   调用   语句   UNC   

1.为什么需要函数

实现代码的复用。存在函数提升,且会在变量提升的上面;

2.函数的创建

js中函数语法:

function 函数名(形参){
//函数体
}

调用时:函数名(形参)

注:

(1) 形参参数名可以重复,同名的形参参数取最后一个值

function test(x,x){
  console.log(x)  
}

test(3,5)//结果:5

 

(2) 即使函数声明了形参,调用时也可以不传递参数值

function test(x){
  console.log(x)  
}

test()//结果:undefind

(3) 调用函数的时候可以传递若干个实参参数值给函数,而不管形参声明时要求的个数

function test(x){
  console.log(x)  
}

test(1,2,3)//结果:1

    在函数的内部,存在一个伪数组对象。所谓伪数组,就是指长得像数组,但是不是真的数组。

  我们可以使用数组的方法来检验这个arguments是否是数组

 

function test(x){
  console.log(x) //1
  console.log(arguments[0]);//1
  console.log(arguments[1]);//2
  console.log(arguments[2]);//3
  console.log(arguments[3]);//undefind 形参只有3个
}

test(1,2,3)//结果:1

 

3.函数的返回值

(1) 当函数执行完毕后,我们可以返回一个值,返回的值的关键字为return。

function test(){
  return 100;
  return 200;  
}
let i =test();
console.log(i);//100

(2) 在JS里面,即使不书写return,也会拥有返回值,返回一个undefined

 

function test(){
  console.log("Hello") 
}
let i =test();
console.log(i);
//Hello
//undefind

 

注:

  需要注意函数里面一旦运行到return,函数的运行就结束了。换句话说,return后面的语句是不会执行的

 

JavaScript 函数

标签:使用   就是   函数名   数组   java   IV   调用   语句   UNC   

原文地址:https://www.cnblogs.com/nailc/p/9186705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!