Search code examples
javascriptfor-loopinheritancecodeceptjs

How can I call an xpath using i to increment the variable name in a for loop using Javascript?


Here are my simple globals which are called by EX: this.u5boys outside of a loop.

u5boys: {
    xpath: "option[contains(text(), '5 Boys')]"
  },
  u6boys: {
    xpath: "option[contains(text(), '6 Boys')]"
  },

Here is a simple loop that will try to click on the literal string "this.u5boys" when run. how do I make it process the this.u5boys into the global xpath identifier stated above in the same file?

ctrlClick5To6Folders(){

    for(var i = 5; i < 7; i++){
      boysaction = "this.u" + i + "boys";
      I.click(boysaction);
    }

  },

How do I tell it to process the value of this.u5boys before running the I.click()function?


Solution

  • it comes out as "this.u5boys"

    And that's normal, given this:

    for(var i = 5; i < 7; i++){
      boysaction = "this.u" + i + "boys";
      I.click(boysaction);
    }
    

    boysaction = "this.u" + i + "boys"; "boysaction" is just a string object in this context.

    Something like this should work

    for(var i = 5; i < 7; i++){
      boysaction = "this.u" + i + "boys";
      I.click(window[boysaction].xpath);//this one
      I.click(this[boysaction].xpath);//or this one
    }
    

    Here, "boysaction" is the string that represents the name of the variable available in the window context.