javascript - Sum of array elements counted dynamic by JS/jQuery -
i have loop this:
while((numbers[0]+numbers[1]+numbers[2]+numbers[3]+numbers[4]+numbers[5]+numbers[6] +numbers[7]+numbers[8]+numbers[9]+numbers[10]+numbers[11]+numbers[12]+numbers[13] +numbers[14]+numbers[15]+numbers[16]+numbers[17]+numbers[18]+numbers[19]+numbers[20] +numbers[21]+numbers[22]+numbers[23]+numbers[24]+numbers[25]+numbers[26]+numbers[27] +numbers[28]+numbers[29]+numbers[30]+numbers[31]) != 0 ) { x=math.floor((math.random() * 32) + 0); if (numbers[x]!=0) { $('.board').append('<div class="tile" data-icon="icon'+(numbers[x])+'" data-end="no"></div>'); numbers[x]=0; } }
i wanna make while condition more sexy. need sum of 'numbers' elements. in loop, values of array elements changing, guess can't count for loop, dynamic counting necessary. function that? i'll grateful solution problem.
use reduce()
es6 arrow function in latest browsers
while(numbers.reduce((a,b) => a+b ) != 0 )
or function
while(numbers.reduce(function(a,b){ return a+b }) != 0 )
for older browser check polyfill option of reduce method.
Comments
Post a Comment