javascript - Create a function that returns an array with all the odd numbers from 5 to 118 - Stack Overflow

Here's my code, but it's not working. Is my thought-process correct? Please help:function sum

Here's my code, but it's not working. Is my thought-process correct? Please help:

function sum_odd(arr) {
   arr = [];
   for (var i = 5; i < 119; i++) {
       if (i % 2 === 1) {
           arr.push(i);
       }
   }
   return arr; 
}

Here's my code, but it's not working. Is my thought-process correct? Please help:

function sum_odd(arr) {
   arr = [];
   for (var i = 5; i < 119; i++) {
       if (i % 2 === 1) {
           arr.push(i);
       }
   }
   return arr; 
}
Share Improve this question edited Aug 15, 2015 at 7:34 Ram 145k16 gold badges172 silver badges200 bronze badges asked Aug 15, 2015 at 7:28 Rory PerroRory Perro 4612 gold badges7 silver badges16 bronze badges 2
  • 4 What does not work? Post a demo to reproduce your issue. – elclanrs Commented Aug 15, 2015 at 7:31
  • 4 I would use for (var i = 5; i < 119; i+=2) {...} as you'll skip the unwanted numbers – Akxe Commented Aug 15, 2015 at 7:39
Add a ment  | 

2 Answers 2

Reset to default 6

Calling sum_odd() returns: [5, 7, 9, 11, 13,..., 117]

Your code works fine but you don't need the arr argument which in fact is not used.

function sum_odd(){
    var arr = [];
    for (var i = 5; i < 119; i++) {
        if (i % 2 === 1) {
            arr.push(i);
        }
    }
    return arr; 
}

var x = sum_odd();
document.write(x);

It is a better idea to save half of the loop iterations and do no checks on i by incrementing i by two.

If you want to modify the argument, remove the var arr = [] statement.

function sum_odd(arr) {
  for (var i = 5; i < 119; i += 2) {
    arr.push(i);
  }
  return arr;
}

var res = [];
sum_odd(res)
document.write(res);

I think the issue you have is not with the actual code, but the way arguments are passed. When you call arr=[], it does not mutate, or change, the original array to be an empty array.

What it does is it redirects the reference that the function holds--the variable arr once held a reference to the parameter passed, but after you assign it to [], it is no longer pointing to the parameter, but it is instead pointing to a new array somewhere else that's initialized to be empty.

So if you run the code

array = [];
sum_odd(array);

Then the sum_odd function does not modify the array passed; instead, it creates a new array and returns it, and in this case the return value isn't used, so array remains empty.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744740361a4590990.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信