简体   繁体   English

创建一个函数,返回一个包含5到118之间所有奇数的数组

[英]Create a function that returns an array with all the odd numbers from 5 to 118

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; 
}

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

Your code works fine but you don't need the arr argument which in fact is not used. 您的代码工作正常,但您不需要实际上未使用的arr参数。

 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. 保存一半的循环迭代是一个更好的主意,并且通过将i 递增2来不对i进行检查

If you want to modify the argument, remove the var arr = [] statement. 如果要修改参数,请删除var arr = []语句。

 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. 当您调用arr=[] ,它不会将原始数组更改或更改为空数组。

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. 它的作用是重定向函数所持有的引用 - 变量arr曾经对传递的参数进行了引用,但在将其赋值给[] ,它不再指向参数,而是指向在其他地方初始化为空的新数组。

So if you run the code 所以如果你运行代码

array = [];
sum_odd(array);

Then the sum_odd function does not modify the array passed; 然后sum_odd函数不会修改传递的数组; instead, it creates a new array and returns it, and in this case the return value isn't used, so array remains empty. 相反,它创建一个新数组并返回它,在这种情况下,不使用返回值,因此array保持为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM