Home > database >  Function invoked inside its body in for loop takes last value instead of sequence value
Function invoked inside its body in for loop takes last value instead of sequence value

Time:04-28

I have an array of objects:

this.array = [{name: null}, {name: null}, {name: null}]

and array of reservend names:

this.reserved = ["name2", "name3"]

I loop through array and try to set uniques name (not included inside reserved array)

  for (let i = 0; i < array.length; i  ) {
    this.setDefaultName(array[i], 1);
  }

  private setDefaultName(obj, index){
    if (!this.reserved.includes(`name${index}`)) {
      obj.name = `name${index}`;
      this.reserved.push(`name${index}`);
    } else {
      return this.setDefaultName(obj, index   1);
    }
  }

After that all objects from array have name "name3". The expected result is to have sequence unique name: "name1", "name4", "name5". Could anyone help me?

CodePudding user response:

I adjust some of your code to make it runnable on snippet. It looks like it works though. Can you recheck?

let nameArray = [{name: null}, {name: null}, {name: null}]
let reserved = ["name2", "name3"]

for (let i = 0; i < nameArray.length; i  ) {
  setDefaultName(nameArray[i], 1);
}

function setDefaultName(obj, index){
  if (!reserved.includes(`name${index}`)) {
    obj.name = `name${index}`;
    reserved.push(`name${index}`);
  } else {
    return this.setDefaultName(obj, index   1);
  }
}

console.log(nameArray)

CodePudding user response:

I created a StackBliz demo which is as close as possible to your code and it is actually working fine! You may compare this demo with yours: StackBliz Demo

  • Related