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

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

#1

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)

#2

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?


#3

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


#4

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


#5

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)) // 

#6

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.


#7

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


#8

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.


#9

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…