search

Home  >  Q&A  >  body text

javascript - 在这两段代码中为什么用return才能实现?用alert却不能呢?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<code>/* function sum_num(){ 

    var total = 0; 

    for(var i=0;i<arguments .length;i++){ 

        total+=arguments[i]; 

    

    return total; 

 

alert(sum_num(2,34,45,56,56)); */

 

 function sum_num(){ 

    var total = 0; 

    for(var i=0;i<arguments .length;i++){ 

        total+=arguments[i]; 

    

     alert(sum_num(total));

 

sum_num();

 

</code>

求大神解答呀?

迷茫迷茫2912 days ago353

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-10 14:57:09

    你的代码应该是递归调用sum_num了,可以写成alert(total)。

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 14:57:09

    递归调用sum_num

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-10 14:57:09

    同意楼上。。

    1

    2

    <code>javascript</code><code>alert(sum_num(total)); // 这里岂不是递归了,改为alert(total)就OK了

    </code>

    reply
    0
  • 迷茫

    迷茫2017-04-10 14:57:09

    InternalError: too much recursion

    ... for(var i=0;i<arguments .length;i++){
    total+=arguments[i];
    } ...

    使用递归去实现你期望的逻辑是错误的,你期望的是获取所有的参数的和,但是你的递归没有结束条件,所以导致死循环,但是就算是有结束条件,递归也不是这么用的

    reply
    0
  • Cancelreply