Advertisement
bayangarkov

checkArrayAndSum

Jan 19th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var arr = [1, 2, 3];
  2.  
  3. function validateArr(arr){ // validate if items contains only numbers
  4.     var i = 0;
  5.     var l = arr.length;
  6.     var areNumber = true;
  7.  
  8.     for (i; i< l; i++){   // check if ALL items are numbers, for every "success check" counter ++
  9.         counter = 0;
  10.         if(isNaN(arr[i])){
  11.             areNumber = false;
  12.         }
  13.         else{
  14.             counter++;
  15.         }
  16.     }
  17.     if(counter === l){    // here check if the counter value are equal to length of the array
  18.         areNumber = true;
  19.     }
  20.  
  21.     return areNumber;
  22. }
  23.  
  24. function sumItems(arr){   // here we sum every item of the array
  25.     var i = 0;
  26.     var l = arr.length;
  27.     var result = 0;
  28.     for (i; i< l; i++){
  29.         result = result + arr[i];
  30.     }
  31.     return result;
  32. }
  33.  
  34. if(validateArr(arr) == true){ // output the result if everything is fine
  35.     console.log(sumItems(arr));
  36. }
  37. else{
  38.     console.log("error");
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement