三 JS的流程控制和函数
3.1 JS分支结构
if结构
-  这里的if结构几乎和JAVA中的一样,需要注意的是 - if()中的非空字符串会被认为是true
- if()中的非零数字会被认为是true
 
-  代码 
if('false'){// 非空字符串 if判断为true
    console.log(true)
}else{
    console.log(false)
}
if(''){// 长度为0字符串 if判断为false
    console.log(true)
}else{
    console.log(false)
}
if(1){// 非零数字 if判断为true, 负数也是true
    console.log(true)
}else{
    console.log(false)
}
if(0){
    console.log(true)
}else{
    console.log(false)
}
结果

switch结构
-  几乎和JAVA的语法一致 
-  代码 
var monthStr=prompt("请输入月份","例如:10 ");
var month= Number.parseInt(monthStr)
switch(month){
    case 3:
    case 4:
    case 5:
        console.log("春季");
        break;
    case 6:
    case 7:
    case 8:
        console.log("夏季");
        break;
    case 9:
    case 10:
    case 11:
        console.log("秋季");
        break;
    case 1:
    case 2:
    case 12:
        console.log("冬季");
        break;
    default :
        console.log("月份有误")
}
效果

3.2 JS循环结构
while结构
-  几乎和JAVA一致 
-  代码 
/* 打印99 乘法表 */
var i = 1;
while(i <= 9){
    var j = 1;
    while(j <= i){
        document.write(j+"*"+i+"="+i*j+"     ");
        j++;
    }
    document.write("<hr/>");
    i++;
}
效果

for循环
-  几乎和JAVA一致 
-  代码 
/* 打印99 乘法表 */
for(  var i = 1;i <= 9; i++){
    for(var j = 1;j <= i;j++){
        document.write(j+"*"+i+"="+i*j+"     ");
    }
    document.write("<hr/>");
}
效果

foreach循环
-  迭代数组时,和java不一样 - 括号中的临时变量表示的是元素的索引,不是元素的值,
- ()中也不在使用: 分隔,而是使用 in 关键字
 
-  代码 
var cities =["北京","上海","深圳","武汉","西安","成都"]
document.write("<ul>")
for(var index in  cities){
    document.write("<li>"+cities[index]+"</li>")
}
document.write("</ul>")
效果

3.3 JS函数声明
JS中的方法,多称为函数,函数的声明语法和JAVA中有较大区别
- 函数说明 
  - 函数没有权限控制符
- 不用声明函数的返回值类型,需要返回在函数体中直接return即可,也无需void关键字
- 参数列表中,无需数据类型
- 调用函数时,实参和形参的个数可以不一致
- 声明函数时需要用function关键字
- J函数没有异常列表
 
- 代码
/* 
语法1 
    function 函数名 (参数列表){函数体}
            */
function sum(a, b){
    return a+b;
}
var result =sum(10,20);
console.log(result)
/* 
语法2
    var 函数名 = function (参数列表){函数体}
            */
var add = function(a, b){
    return a+b;
}
var result = add(1,2);
console.log(result);
调用测试




















![BUUCTF[PWN][fastbin attack]](https://img-blog.csdnimg.cn/img_convert/f4d6c22660d4d1fc1e551769a12ef9de.png)