0

I am trying to figure out what likely is simple. I have a for loop of unknown length. I'd like to do something like the following where nearby_ports_x gets x from the loop. So I might have nearby_ports_0 ... nearby_ports_x The nearby_port_x ... would the be use to post


for (x = 0; x < document.getElementsByClassName("nearby_ports").length; x++) {
    nearby_ports_x = document.getElementsByClassName("nearby_ports")[x].href;
}
  • btw use `let` instead of `int`, since `int` isn't a thing in javascript – Samathingamajig Jun 23 '22 at 18:59
  • What is `nearby_ports_x ` ? do you want everything to += it? (concat) – IT goldman Jun 23 '22 at 18:59
  • @ITgoldman I think they want `nearby_ports_0`, `nearby_ports_1`, ..., `nearby_ports_534`, etc. – Samathingamajig Jun 23 '22 at 18:59
  • Calling Dr. Eval – IT goldman Jun 23 '22 at 19:00
  • @ITgoldman don't suggest `eval`. It's a terrible practice. – VLAZ Jun 23 '22 at 19:01
  • 1
    OP, there is (almost always) no reason to make variables the way you're wanting to. Create an array/object instead that you would access as `nearby_ports[0]`, `nearby_ports[1]`, etc. – Samathingamajig Jun 23 '22 at 19:01
  • @VLAZ it is bad practice if you run it on user input. Sometimes there's no other option. For example https://stackoverflow.com/questions/72696657/how-to-change-the-placeholder-value-for-a-dynamically-fetched-text/72696895#72696895 – IT goldman Jun 23 '22 at 19:02
  • @ITgoldman it's almost never the only option. Unless you've taken several wrong steps way before you got to that point. It's a terrible practice because it has some unintuitive semantics to it. Moreover, you have to write code that produces other code. And there are a bunch of potential pitfalls to that practice as well. And above all, you have to do all of that *instead of* writing proper code that correctly lays own instructions to achieve an effect. Which you can further enhance in various programmatic ways. `eval` doesn't even allow syntax highlighting - the first protection against bugs. – VLAZ Jun 23 '22 at 19:09
  • @ IT goldman I have a api that currently would accept in the form nearby_ports_0 ... nearby_ports_10 – AlwaysResearching Jun 23 '22 at 19:10
  • @AlwaysResearching I know I offered to use `eval` see duplicate answer. @VLAZ yes but sometimes it's the only option if some1 else took the wrong steps for you. Besides, you have to admit it's most awesome function and the most dreaded one. – IT goldman Jun 23 '22 at 19:13
  • @Samathingamajig yes although I am trying to post to an api which requires – AlwaysResearching Jun 23 '22 at 19:13
  • @AlwaysResearching please include more details. Posting to an API does not send the name of your variables (it does a similar thing though if you create an object and serialize it to json) – Samathingamajig Jun 23 '22 at 19:15

0 Answers0