Summation Array without undefined nums in array and [NO METHOD]

How do I sum array without full array of nums ? Any idea ?

var nums = [];
var sum = 0;
for(var i=0; i<100; i++){
	nums[i] = nums;
	sum = nums[i];
}
console.log(sum)

I didn’t properly get you question.
But, it seems you want to add the elements of aay and you do not know the number of elements in it.
So, see if this works for you:

nums.reduce((a,b) => a+b);

Does this help?

Thanks. I know this method. I need for loop with defined empty array. I want to used numbers in range of for loop.

Hi there.
And you want to sum all digits generated within a loop?

yes of course.

I do not enter the digitt of nums. I don’t want to type of belowing functions. Any idea ?

function sum (n) {
  let sum = 0
  
  for (let i = 1; i <= n; i ++) {
    sum += i
  }
  
  return sum
}

console.log(sum(10)) // 

You can use while loop or reduce but JS don’t have default method to sum all digits from 0 to N . You have to write similar to yours code.

Thanks. I don t want to write with special methods such as reduce, etc.

Are you sure you want to set the i-th member of nums to the complete nums array? I might suggest you set the i-th member of nums to i instead:

var nums = []; 
 var sum = 0; 
for(var i=0; i<100; i++){
  // set the last member of nums to the index value 
  nums[i] = i;
  // add that value to the sums variable
  sum += nums[i];
}
console.log(sum);

You can’t sum your current nums array, because (I think) its an infinitely nested array.

1 Like

Also, comment your code. It’s a thing I tend to harp on, but you will find it makes it easier to debug later – if your comment says to expect one behavior, and a console.log statement shows another behavior entirely…

1 Like