Hatem Husam
Hatem Husam

Reputation: 187

Dynamic name for JS variable

Can you please guide me how to replace a long javascript with a loop or something similar? I've to create some variables and after that call a method after each key press.

var list1 = new List('list1', options);
var list2 = new List('list2', options);
var list3 = new List('list3', options);
var list4 = new List('list4', options);
var list5 = new List('list5', options);
var list6 = new List('list6', options);
var list7 = new List('list7', options);
var list8 = new List('list8', options);
var list9 = new List('list9', options);
var list10 = new List('list10', options);
var list11 = new List('list11', options);

$('.search-field').on('keyup', function () {
    window.scrollTo(0, 0);
    list1.search($(this).val());
    list2.search($(this).val());
    list3.search($(this).val());
    list4.search($(this).val());
    list5.search($(this).val());
    list6.search($(this).val());
    list7.search($(this).val());
    list8.search($(this).val());
    list9.search($(this).val());
    list10.search($(this).val());
    list11.search($(this).val());
});

Upvotes: 0

Views: 93

Answers (2)

Cuong Vu
Cuong Vu

Reputation: 3723

You can replace your code with this. Start with an empty array. Then use a for loop to add elements, then use another for loop to call function

const list = [];
for (let i = 0; i < 11; i++) {
  list[i] = new List('list' + i, options);
}


$('.search-field').on('keyup', function () {
  window.scrollTo(0, 0);
  for (let i = 0; i < 11; i++) {
    list[i].search($(this).val());
  }

});

Upvotes: 0

Michał Z.
Michał Z.

Reputation: 1392

You can group your variables as array or object.

For example (variables in object):

const n = 11;
var lists = {};

for(let i=1;i<=n;++i) {
    lists['list'+i] = new List('list'+i, options);
}

$('.search-field').on('keyup', function () {
    window.scrollTo(0, 0);
    for(let i=1;i<=n;++i) {
        lists['list'+i].search($(this).val());
    }
}

Where object key is "variable name" and value for that key is just value

object[key] = value // write value
object[key]         // read value

Upvotes: 2

Related Questions