最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

The sum of a range using Javascript - Stack Overflow

programmeradmin0浏览0评论

I wish to execute a program with output as :

console.log(range(1, 10));  
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
console.log(range(5, 2, -1));  
// → [5, 4, 3, 2]  
console.log(sum(range(1, 10)));  
// → 55  

I am getting an error for array.length.Please find the code below:

var array = [];

function range (arr){  
    var lower = Math.min(arr[0],arr[1]);    
    var upper = Math.max(arr[0],arr[1]);  

    for (var i=lower;i<=upper;i++){  
        array.push(i);  
    }  
}  

function sum(array){  
    for(var i=0;i < array.length;i++){  
        var total = total+array[i];  
    }  
}  

console.log(sum(range(1, 10)));  

I am at begineers level, please do help. Thanks.

I wish to execute a program with output as :

console.log(range(1, 10));  
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
console.log(range(5, 2, -1));  
// → [5, 4, 3, 2]  
console.log(sum(range(1, 10)));  
// → 55  

I am getting an error for array.length.Please find the code below:

var array = [];

function range (arr){  
    var lower = Math.min(arr[0],arr[1]);    
    var upper = Math.max(arr[0],arr[1]);  

    for (var i=lower;i<=upper;i++){  
        array.push(i);  
    }  
}  

function sum(array){  
    for(var i=0;i < array.length;i++){  
        var total = total+array[i];  
    }  
}  

console.log(sum(range(1, 10)));  

I am at begineers level, please do help. Thanks.

Share Improve this question edited Apr 19, 2016 at 12:36 gaurav sharma asked Apr 19, 2016 at 12:18 gaurav sharmagaurav sharma 571 gold badge1 silver badge6 bronze badges 2
  • 2 dude while calling your range function pass the arguments as range([1,10]) – Manish Commented Apr 19, 2016 at 12:22
  • Should the range(5, 2, -1) ==> [-1, 0, 1, 2, 3, 4, 5]?? – Jagdish Idhate Commented Apr 19, 2016 at 12:38
Add a comment  | 

12 Answers 12

Reset to default 4

You have a few problems here:

1.) You aren't returning anything in your range function. You need to return the filled array.

2.) You aren't passing the array correctly in the sum function call.

3.) You aren't returning anything in your sum function call.

Without returning any values, you aren't letting your code blocks work with eachother

var array = [];

function range (arr){  
    var lower = Math.min(arr[0],arr[1]);    
    var upper = Math.max(arr[0],arr[1]);  

    for (var i=lower;i<=upper;i++){  
        array.push(i);  
    }
    return array; // return the array to be used in the sum function
}  

function sum(array){  
    var total = 0; // need to create a variable outside the loop scope
    for(var i in array){  
       total = total+array[i];  
    }
    return total;
}  

console.log(sum(range([1,10]))); // pass the array correctly 

Note that you need to set the total variable outside the scope of the for-loop within the sum function. That way you can return the final value. Otherwise, it would return undefined.

See the fiddle: https://jsfiddle.net/udyhb95a/

  1. You need to pass an array when calling the range function you defined range([1, 10])

  2. You need to rewrite your sum function

As a side note, there are more efficient ways to compute the sum of a range of elements without iterating on them.

function sum_of_range(start, end) {
    return end * (end + 1) / 2 - start * (start + 1) / 2;
}

Edit:

Here is a working sum function

function sum(array) {
    var accumulator = 0;
    for (var i = 0; i < array.length; ++i)
        accumulator += array[i];
    return accumulator;
}

Here you declare a function with one parameter as an array

function range (arr){ 
      ...

But here you call a function with two arguments as numbers

console.log(range(1, 10)); 

Use this call function

console.log(range([1, 10])); 

And don't use for..in for arrays

for(var i in array){ it doesn't work as you expect 

Use forEach function or plan for loop

Also you have some error in sum function

See working example below:

function range(arr) {
    var array = [];
    var lower = Math.min(arr[0], arr[1]);
    var upper = Math.max(arr[0], arr[1]);

    for (var i = lower; i <= upper; i++) {
        array.push(i);
    }
    return array;
}

function sum(array) {
    var total = 0;
    for (var i  = 0; i < array.length; i++) {
        total = total + array[i];
    }
    return total;
}

document.write('range ' + range([1, 10]) + '<br>');
document.write('sum ' + sum(range([1, 10])));

You need to modify sum & range function

function range (){
    var array = []; 
    var lower = Math.min.apply(null, arguments);    
    var upper = Math.max.apply(null, arguments);    

    for (var i=lower;i<=upper;i++){  
        array.push(i);  
    }
    return array;  
} 

function sum(array){  
    return  array.reduce((x,y)=>x+y,0);
} 

console.log(range(1, 10)); 
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1)); //if we are considering min & max from params
// [-1, 0, 1, 2, 3, 4, 5]
console.log(sum(range(1, 10)));
// 55

Hello Dear check it now.

                var array = [];

                function range(arr, arr1) {
                    var lower = Math.min(arr);
                    var upper = Math.max(arr1);
                    for (var i = lower; i <= upper; i++) {
                        array.push(i);
                    }
                }

                function sum() {
                    var total = 0;
                    for (var i = 0; i < array.length; i++) {
                        total = total + array[i];
                    }
                    return total;
                }
                console.log(sum(range(1, 10)));

This is the correct answer to the problem at the end of the data structures chapter within Eloquent JavaScript

function range(start, end, step) {
  let arr = []; //declare an empty array
  var step = step || 1;//tests to see if step was supplied, otherwise it's 1
  if(start < end) 
  {
    for(let i = start; i <= end; i += step)
    {
      arr.push(i);
    }
  }
  else 
  {
    for(let i = start; i >= end; i += step)
    {
      arr.push(i);
    }
  }
  return arr;
}
function sum(array) {
  let total = 0;
  for(let i = 0; i < array.length; i++) 
  { 
    total += array[i];
  }
  return total;
}

console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1,10)));
// → 55

This solution takes into account of entering a step that isn't expected to be positive/negative, i.e range from 1 to 5, we would expect step to be positive, but if the user somehow entered a negative step then an empty array would occur.

The browser actually hangs for the opposite, if the array is expected to decrease, but the step sizes are > 0.

'use strict';

function range(start, end, step = 1){
    let output = [];

    if (start > end){
        // Sanity check, all steps if expected to go down should be negative
        if (step > 0){
            step = -step;
        }

        for (;start >= end; start += step){
            console.log(start);
            output.push(start);
        }
    }
    else{
        // Likewise, as all steps should be positive
        if (step < 0){
            step = -step;
        }

        for (;start <= end; start += step){
            output.push(start);
        }
    }
    return output;
}

function sum(arr){
    let output = 0;
    for (let i of arr){
        output += i;
    }
    return output;
}

console.log(range(1, 5, 1));
// → [1, 2, 3, 4, 5]

console.log(range(5, 1, -1));
// → [5, 4, 3, 2, 1]

// Notice this one step is a positive, but this is handled (original solution returned empty array)
console.log(range(5, 1, 1));
// → [5, 4, 3, 2, 1]

console.log(sum(range(1,10)));
// → 55

An improvement onto this is to use the reduce function for an array to sum instead of a for loop, i.e:

function sum(array){  
    return array.reduce((x,y)=>x+y,0);
} 

For people finding this later on as I did, here is a way to write the range function so you can pass the input as written in the original question:

console.log(sum(range(1, 10)));

…and a cleaned up sum function similar to the one in A. Sharma's answer:

function range(lower, upper) {
  let array = []
  for (let i = lower; i <= upper; i++) {
    array.push(i);
  }
  return array;
}

function sum(array) {
  let total = 0;
  for (let i in array) {
    total = total + array[i];
  }
  return total;
}

console.log(sum(range(1, 10)));

Also worth mentioning:

  • The use of reduce in JagsSparrow's answer, which is elegant, while not entirely obvious and newcomer friendly as Mathias Vonende pointed out.
  • Negative step tolerant versions in answers from Jimmy Wei and user3225968.

This is the best solution I've got

function range(x,y){
    var arr = [];
    for(x;x<=y;x++){
        arr.push(x);
    };
    return arr;
};

function sum(array){
    return array.reduce((a,b) => a + b, 0);
};

console.log(sum(range(1,10)));

This answer is quite late but I am learning these things now and want to share my solution. I have not seen this solution provided for the specific question "Sum of a range in Javascript" so I wanted to share it. What I have done here is made use of the pop method for the array which allowed me not to specifically pass an array argument to the range function but to provide a solution to the argument in the way it was originally presented in the question.

var result = [];
var counter = 0;
function range(start, end) {
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
}

function sum(array) {
    for (let i = 0; i < result.length; i++) {
      counter += result.pop(i);
    }
    return counter;
}

console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(sum(range(1, 10)));
// → 55

This can be accomplished very easily and efficiently without any globally scoped vars.

It's not clear in the original question what behavior should be applied to the -1 argument. It seems to be an indicator to reverse the range. In the below example, I've used a boolean to check this argument. A value of -1 would actually be the same as not providing a third argument. To reverse the range, pass in any truthy value.

function range(from, to, reverse) {
  // Make sure our inputs are actually numbers
  if (Number(from) != from || Number(to) != to) {
    throw new TypeError("range() expects a Number as both it's first and second argument");
  }

  let o = []; // initialize our output array
  
  // get the lowest value argument as our starting index
  let i = Math.min(from, to);
  
  // get the highest value argument as our ending index
  let x = Math.max(from, to); 

  // push i onto our output array and then increment until i == x
  while (i <= x) { o.push(i); i++; }

  // reverse the range order if necessary
  if (reverse) { o = o.reverse(); }
  
  // return our output array
  return o;
}

Then we can use Array.reduce to iterate through the range array and add each value (b) to the one before it (a) with the addition assignment operator (+=).

function sum(range) {
  if (!(range instanceof Array)) {
    throw new TypeError("sum() expects an Array as it's only argument");
  } return range.reduce((a,b) => a+=b);
}

Testing it:

let a = range(1,10);
let b = range(5,2);
let c = range(5,2,true);
let d = range(3,-1);
let e = range(10,10);

console.log(a); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(b); // [ 2, 3, 4, 5 ]
console.log(c); // [ 5, 4, 3, 2 ]
console.log(d); // [ -1, 0, 1, 2, 3 ]
console.log(e); // [ 10 ]
console.log(range('test', 10)); // TypeError
console.log(range(1, 'test')); // TypeError

console.log(sum(a)); // 55
console.log(sum(b)); // 14
console.log(sum(c)); // 14
console.log(sum(d)); // 5
console.log(sum(e)); // 10
console.log(sum('test')); // TypeError

here my answer, I'd glad if you give me feedback about this solution.

let arr = [];

function range(x, y) {
for (let i = x; i <= y; i++) {
    arr.push(i);
}
return arr;
}

function sum(array) {
const many = array.reduce((total, number) => {
    return total + number;
}, 0);
return many;
}

console.log(sum(range(1, 10)));
发布评论

评论列表(0)

  1. 暂无评论