[英]Need help finding the sum of all numbers in an array
我試圖找到所有低於1000的3或5的數字。獲得所有數字后,我想將它們加起來。
我能夠弄清楚如何找到倍數並將它們添加到數組中,但無法弄清楚如何將它們加在一起。
這是我的代碼:
var add = [];
var count = 0;
if ( i % 3 == 0 || i %5 == 0) {
for (var i = 1; i <= 1000; i ++) {
add.push(i);
}
};
function whole () {
for(var i = 0 ; i <= add.length; i ++) {
count = count + add[i];
}
};
whole();
第一個循環永遠不會發生,因為那時i
是undefined
(i%3是NaN)。
我認為您只需要使用if
反轉for
。
for (var i = 1; i <= 1000; i ++) {
if ( i % 3 == 0 || i %5 == 0) {
add.push(i);
}
};
需要返回count
的斷言是不正確的。 該功能將僅對全局count
起作用。
一種更清潔,功能上純凈的方式來執行此操作:
function whole(i, count, max){
if(i > max){
return count;
}
if(i % 3 === 0 || i % 5 === 0){
return whole(i + 1, count + i, max);
}
return whole(i + 1, count, max);
}
whole(0, 0, 1000);
您需要將條件放入循環中,並讓循環運行直到i < 1000
因為您只希望數字小於1000。
for (var i = 1; i < 1000; i ++) {
if (i % 3 == 0 || i %5 == 0) {
add.push(i);
}
}
在整個函數中,您需要運行i < add.length
,否則您將嘗試向未加和添加未定義的索引。
function whole () {
for(var i = 0 ; i < add.length; i ++) {
count = count + add[i];
}
};
這是對數字數組求和的一種更好的方法。
您可以在數組上使用reduce函數來獲取“ reduce ”值
add.reduce(function(x,y) { return x+y; }, 0);
例如((0 + 1) + 2) + 3
將返回6
[1,2,3].reduce(function(x,y) { return x+y; }, 0); //=> 6
這是使用功能更強大的方法潛在解決問題的另一種有趣方法。
它使用ES6 ,但不用擔心。 您可以輕松地將示例復制/粘貼到babeljs.io/repl中,以查看其運行情況。 Babel還將為您提供等效的ES5。
// let's say we have an array of 1000 numbers
let ns = new Array(1000);
// fill the array with numbers
for (let i=0, len=ns.length; i<len; i++) {
ns[i] = i+1;
}
// some reusable functions
let mod = y => x => x % y;
let eq = y => x => x === y;
let id = x => x;
let filter = f => xs => xs.filter(f);
let reduce = f => i => xs => xs.reduce(uncurry(f), i);
let comp = g => f => x => g(f(x));
let compN = reduce(comp)(id);
let uncurry = f => (x,y) => f(x)(y);
// these are some helpers you could define using the reusable functions
let add = y => x => x + y;
let sum = reduce(add)(0);
let divisibleBy = x => comp(eq(0))(mod(x));
// define your solution as a composition
// of `sum`, `divisbleBy(5)`, and `divisibleBy(3)`
let solution = compN([
sum,
filter(divisibleBy(5)),
filter(divisibleBy(3))
]);
// output the solution passing in the original `ns` array
console.log(solution(ns));
我認為你很親密。 在整個函數中,您需要返回count。
function whole () {
for(var i = 0 ; i <= add.length; i ++) {
count = count + add[i];
}
return count;
};
只需調用reduce而不使用start參數。
arr.reduce(callback [,initialValue]):
If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.
MDN
add.reduce(function(x, y) { return x + y; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.