JavaScript教程:return

说明

return 在 函数中使用,表示返回值

用法一

普通用法

function add(a , b){
    var res = a + b
    return res
}

用法二

在 if 语句中使用

注意: 不推荐这么写

function pingjia(score){
    if(score>=90){
        return "优" 
    }else if(score>=80){
        return "良"
    }else if(score>=70){
        return "中"
    }else if(score>=60){
        return "及格"
    }else{ // 没有必要再做判断
        return "不及格"
    }
}

var res = pingjia(92)
console.log("res=",res)

用法三

在 循环语句中使用

function game(){
    for( var i=1 ; i <= 20 ; i++ ){

        if( i%7 == 0 ){ // 表示 7 的倍数
            return i  // 当i为7时,就返回(终止循环)  注意:return 要在函数中,不在函数中会报错
        }
        console.log(i)
    }
}

var res = game()

console.log("res=",res)

原文出处:/show_1IX3AS0wqV0G.html