文章目录

  • 一、循环
  • 1.while循环
  • 2.for循环
  • 3.for...in循环
  • 4.中断循环
  • 二、函数
  • 1.普通函数
  • 2.匿名函数
  • 3.返回匿名函数
  • 4.立即执行函数
  • 三、作用域
  • 1.全局作用域(整个script标签)
  • 2.局部作用域(函数内部)
  • 四、事件
  • 1.行内式调用
  • 2.函数式调用
  • 总结



一、循环

1.while循环

基本格式:

while(条件){
//js语句
}

代码如下(示例):

var i = "";  
while (input != "js") {  
   input = prompt("请输入 \"js\"");  
}

2.for循环

基本格式:

for(初始化参数;循环条件;增量或减量){
   //js语句
}

代码如下(示例):

document.write("<table><tr>")  
for (var i = 1; i < 10; i++) {  
    for (var j = 1; j <= i; j++) {  
        document.write("<td>"+ j +"*"+ i 
        + "="+ i*j +"</td>")
    }  
    document.write("</tr>")  
} 
document.write("</table>")

3.for…in循环

基本格式:

for(变量名 in 对象名){
//js语句
}

代码如下(示例):

var cars = ["Audi", "Volvo", "BMW", "Benz"]  
for (var i in cars) {  
    document.write(cars[i] + "<br/>");  
}

4.中断循环

break:
立即退出整个循环,一个break只能退出一个循环

代码如下(break示例):

for(var i=0; i<5;i++){  
if (i==2) {
	break;    
}
console.log(i);  //输出0、1 
				//当i=2时退出循环,后面的不在继续执行
}

continue:
跳过当前循环,不会退出整个循环

代码如下(continue示例):

for(var i=0; i<5;i++){  
if (i==2) {
	continue;    
}
console.log(i);  //输出0、1、3、4 
				//当i=2时;跳过当前循环,继续执行后面的循环
}

二、函数

1.普通函数

基本格式:

function name(参数1, 参数2, 参数3) {
    //要执行的代码
  return 返回值
}

代码如下(示例):

function add(a, b) {  
    return a + b  
}  
var result = add(1, 2);  //调用函数
console.log(result);

2.匿名函数

基本格式:

function (参数1, 参数2, 参数3) {
    //要执行的代码
  return 返回值
}

代码如下(示例):

var add = function (a, b) {   //add存的函数
    return a + b  
}  
var result = add(1, 2);  //调用函数
console.log(result);

3.返回匿名函数

基本格式:

function name(参数1, 参数2, 参数3) {
    //要执行的代码
  return 匿名函数
}

代码如下(示例):

function getAdd() {  
    return function(a, b) {  
        return a + b;  
    }  
}  
var add = getAdd();  
var result = add(1, 2);  
console.log(result);

4.立即执行函数

不用调用,直接执行

基本格式:

(function name(参数1, 参数2, 参数3) {
    //要执行的代码
  return 返回值
})(参数1,参数2, 参数3)

代码如下(示例):

(function getAdd() {  
    return function(a, b) {  
        console.log(a+b);  //输出3
    }  
})(1,2)

三、作用域

1.全局作用域(整个script标签)

var 变量名;
变量名;

代码如下(示例):

var a=1;
b=2;
function myFunction() {   
    console.log(a); //此处可以访问 
    console.log(b); //此处可以访问 
}
 console.log(a);  //此处可以访问

2.局部作用域(函数内部)

function () {
var a=1;
}

代码如下(示例):

function myFunction() {   
    var a=1; 
    console.log(a); //此处可以访问 
}
 console.log(a); //此处不可以访问

四、事件

1.行内式调用

基本格式:

<标签名 οnclick=“函数名()”>Hello</标签名>

代码如下(行内式示例):

<button onclick="showHello()">Hello</button> 
<script type="text/javascript">  
function showHello(){  
    alert(“hello”);
} 
</script>

2.函数式调用

基本格式:

var 元素对象=document…getElementById(“id名”);
元素对象.οnclick=function(){};

代码如下(行内式示例):

<button id="show">Hello</button> 
<script type="text/javascript">  
var show=document..getElementById("show");
show.onclick=function(){  
    alert(“hello”);
} 
</script>

总结


注意for...in循环的使用,匿名函数的调用,分清局部作用域和全局作用域。