为什么在 cosole 之前返回语句.log会影响 JavaScript 中的整个函数



我写了下面的脚本,它应该计算一个数字的一半,它的平方根,圆的面积以及平方根和面积的百分比。

但是,当我编写脚本时,我在执行空间中使用了 return 语句,后跟 console.log(),当我这样做时发生了语法错误,但是当我声明 console.log() 后跟 return 时,代码似乎工作正常。

这是我的代码。

好代码:

function squareNumber(num){
    var squaredNumber = num * num;
    console.log(" the square of " + num + " is " + squaredNumber);
    return squaredNumber;
}

function halfOf(num){
    var half = num / 2;
    console.log(" half of  " + num + " is " + half);
    return half;
}
function percentOf(num1, num2){
    var percent = (num1 / num2) * 100;
    console.log(num1 + " is " + percent + " % of " + num2);
    return percent; 
}

function areaOfCircle(radius){
    var area = 3.14 * radius * radius;
    console.log(" the area of a circle with radius of " + radius + " is  " + area);
    return area;
}
function doCrazyStuff(num){
    var halfy = halfOf(num);
    var squared = squareNumber(halfy);
    var area = areaOfCircle(squared);
    var result = percentOf(area, squared);
}

错误代码:

function squareNumber(num){
    var squaredNumber = num * num;
    return squaredNumber;
    console.log("the square of " + num + " is " + squaredNumber);
}

function halfOf(num){
    var half = num / 2;
    return half;
    console.log(" half of  " + num + " is " + half);
}
function percentOf(num1, num2){
    var percent = (num1 / num2) * 100;
    return percent;
    console.log(num1 + " is  " + percent + " % of " + num2); 
}

function areaOfCircle(radius){
    var area = 3.14 * radius * radius;
    return area;
    console.log(" the area of a circle with radius of " + radius + " is " + area);
}
function doCrazyStuff(num){
    var halfy = halfOf(num);
    var squared = squareNumber(halfy);
    var area = areaOfCircle(squared);
    var result = percentOf(area, squared);
}

return 会停止函数执行,之后不会执行任何其他操作。

不要将代码放在任何语言的 return 语句之后。

最新更新