admin管理员组文章数量:1422955
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
2 Answers
Reset to default 6Calling 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.
版权声明:本文标题:javascript - Create a function that returns an array with all the odd numbers from 5 to 118 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744740360a2622571.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论