Create array with start, end and step - Node.js Array

Node.js examples for Array:Array Operation

Description

Create array with start, end and step

Demo Code


function range(start,end,step) {
  var array = []/*from w ww  . j  a v a 2  s . c om*/
  if (typeof(step)==='undefined') step = 1;
  if (start < end) {
    for (var i=start;i<=end;i+=step) {
      console.log(i)
      array.push(i);
    }
  } else {
    for (var i=start;i>=end;i+=step) {
      console.log(i)
      array.push(i);
    }
  }
  return array;
}

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

console.log(sum(range(1,10)));
console.log(range(5, 2, -1));

Related Tutorials