0
onEvent("pb" + 1, "click", function() {
console.log(("pb" + 1) + " was clicked!");
});

onEvent("pb" + 2, "click", function() {
console.log(("pb" + 2) + " was clicked!");
});

onEvent("pb" + 3, "click", function() {
console.log(("pb" + 3) + " was clicked!");
});

onEvent("pb" + 4, "click", function() {
console.log(("pb" + 4) + " was clicked!");
});

I had to write 80 of these functions...

I'd like to make it so I could use a variable to include the range 1-80:

 onEvent("pb" + [1, 80], "click", function() {
 console.log(("pb" + [1, 80]) + " was clicked!");
 });

I'm not sure if it's possible to define a variable as a set of individual numbers.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Jacobnarg
  • 11
  • 2
  • How about writing a loop and using the index to create all of these `onEvent` params? – ggorlen Apr 17 '20 at 00:50
  • You can use Array.from as Array.from({length: 80}, (v, i) => onEvent("pb" + i, "click", function(){ console.log("pb" + i + " was clicked"); })); – Hien Nguyen Apr 17 '20 at 01:03
  • If `this` refers to the element you're clicking on inside your callback function and the selector supports classes. You could use a class selector instead of an id, and use `this.id` to get the id of the element clicked. – Nick Parsons Apr 17 '20 at 01:05

2 Answers2

1

use a loop:

for (let i = 1; i <= 80; i++) {
    onEvent("pb" + i, "click", function()
        console.log("pb" + i + " was clicked");
    })
}

Make sure you use let rather than var, so that you get a new binding for each iteration. Otherwise you'll run into the Javascript infamous Loop issue?

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Unfortunately, range iterators are not built in yet. But they are simple enough to make (using a loop):

function* range(start, end) {
    for (let i = start; i <= end; i++) {
        yield i
    }
}

Which then lets you do this:

for (let value of range(1,80)){
  console.log(value)
}

or this:

range(1,80).forEach(value => console.log(value))

Why do this instead of just a loop? Well, depends, sometimes a loop makes more sense. But here are some reasons why this might be better:

  • more intention revealing code: having a function named range tells you what you intend to do: work with a range of values
  • better extraction: say you later discover that loops are inefficient (unlikely, but for the sake of example). Then you can change you range code in one place, and fix it everywhere. Or maybe you want to handle making ranges for letters as well as numbers. Now you can make the change in one place, and it works everywhere.
  • Similarly, say you need to use ranges in many places. Using a loop everywhere means that you have to avoid typos every place you use that loop. If instead you use range, you can avoid that issue.
Garrett Motzner
  • 3,021
  • 1
  • 13
  • 30