I’m new to JS function and objects
I’m trying to iterate an array…this is my sample code which i was trying to get the multiples of coins with an input value
var flag=0;var chipval=0;var num=0;
var main = function(coins){
var coinsarr = [1,5,10,25,50,100,500,501];var length=coinsarr.length
var remval = coins;
var coinskey = "";
while(flag==0){
for(i=0;i<length;i++){
if(coinsarr[i]>remval){
chipval = coinsarr[i-1];
num = parseInt(remval/chipval);
if(remval%chipval==0){
flag = 1;
break;
}else{
remval=remval%chipval;
$flag = 0;
break;
}
}
}
coinskey = coinskey+","+chipval+":"+num;
}
coinskey = coinskey.replace(/(^,)|(,$)/g, "")
alert(coinskey);
}
when i run main(120), this will return 100:2,10:2(which is nothing by 100coins of 2 and 10coins of 2)
When i run main(720), i’m getting memory leaks…which says “Script on this page used too much memory”;
Can anyone tell me, where the issue is or else is this the right way to proceed ??
Thanks for your time and patience…
A slightly cleaner option to get a amount of coins to make up a value, would be to build a object containing the values. Something like this will do the trick:
The advantage of this is that you can retrieve the values easier than having to parse a string:
Or just build a string like this: