Home > other >  Javascript for loop function not working in another function
Javascript for loop function not working in another function

Time:03-23

The function "reversedcurrConvert", which contains a for loop and which is called in function checkCashRegister, is working only from index 1 onwards. Curiously it does not work for index 0 which is cid[0][0]. Can't wrap my head around what could've caused this behaviour.

function reversedcurrConvert(cid) {
  for(let i = 0; i < cid.length; i  ) {
    if(i=0) {cid[i][0] = "PENNY"}
    if(i=1) {cid[i][0] = "NICKEL"}
    if(i=2) {cid[i][0] = "DIME"}
    if(i=3) {cid[i][0] = "QUARTER"}
    if(i=4) {cid[i][0] = "ONE"}
    if(i=5) {cid[i][0] = "FIVE"}
    if(i=6) {cid[i][0] = "TEN"}
    if(i=7) {cid[i][0] = "TWENTY"}
    if(i=8) {cid[i][0] = "ONE HUNDRED"}
  }
  return cid
}

function checkCashRegister(price, cash, cid) {
  let change = {}
  
  cid[0][0] = 0.01
  cid[1][0] = 0.05
  cid[2][0] = 0.1
  cid[3][0] = 0.25
  cid[4][0] = 1
  cid[5][0] = 5
  cid[6][0] = 10
  cid[7][0] = 20
  cid[8][0] = 100

  change['status'] = "CLOSED"
  change['change'] = reversedcurrConvert(cid)
  return change

}

checkCashRegister(19.5, 20, [["PENNY", 0.5], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])

CodePudding user response:

The first problem that you must use i == x in your loop instead of i = x. The second problem you do a lot of unnecessary if. Here is example how you can easily set the value by using object as map

function reversedcurrConvert(cid) {
  const banknoteName = {
    0: 'PENNY',
    1: 'NICKEL',
    2: 'DIME',
    3: 'QUARTER',
    4: 'ONE',
    5: 'FIVE',
    6: 'TEN',
    7: 'TWENTY',
    8: 'ONE HUNDRED',
  };
  
  for (let i = 0; i < cid.length;   i) {
    cid[i][0] = banknoteName[i];
  }
  
  return cid;
}

function checkCashRegister(price, cash, cid) {
  let change = {}

  cid[0][0] = 0.01;
  cid[1][0] = 0.05;
  cid[2][0] = 0.1;
  cid[3][0] = 0.25;
  cid[4][0] = 1;
  cid[5][0] = 5;
  cid[6][0] = 10;
  cid[7][0] = 20;
  cid[8][0] = 100;

  change['status'] = 'CLOSED';
  change['change'] = reversedcurrConvert(cid);
  
  return change
}

console.log(checkCashRegister(19.5, 20, [
  ["PENNY", 0.5],
  ["NICKEL", 0],
  ["DIME", 0],
  ["QUARTER", 0],
  ["ONE", 0],
  ["FIVE", 0],
  ["TEN", 0],
  ["TWENTY", 0],
  ["ONE HUNDRED", 0]
]));

P.S. I really didn't clearly understand why you at first time set numbers into cid[x][0] and then set string with for loop. When you pass cid into reversedcurrConvert function you pass pointer to this array not it's copy, if you don't know. Because of it when you change value in your reversedcurrConvert function you also change values of cid in checkCashRegister funcrion. So you can set this strings without looping as you do it before calling reversedcurrConvert function

  • Related