1

How can I reduce the below code? I want to assign multiple variables in fewer lines, perhaps a for loop could help.

let a1 = $('[name="answer[1]"]:checked').val(),
    a2 = $('[name="answer[2]"]:checked').val(),
    a3 = $('[name="answer[3]"]:checked').val(),
    a4 = $('[name="answer[4]"]:checked').val(),
    a5 = $('[name="answer[5]"]:checked').val(),
    a6 = $('[name="answer[6]"]:checked').val(),
    a7 = $('[name="answer[7]"]:checked').val();

What I have tried but not working:

var i;
for (i = 1; i < 8; i++) {
    let a[i] = $('[name="answer['+i+']"]:checked').val();
}

3 Answers3

0

What I can think of is this

var i;
for (i = 1; i < 8; i++) { 
  let a[i] = $('[name="answer['+i+']"]:checked').val();
}
Francesco
  • 429
  • 4
  • 12
0
  for (var i = 0; i < 8; ++i) {
      a[i] = "whatever";
  }

as posted in JavaScript: Dynamically Creating Variables for Loops

Budyn
  • 563
  • 7
  • 21
0

In a browser environment, you can assign variables by setting a property of the window object:

for (let i = 0; i < 8; i++) {
  window["a"+i] = "something "+i;
}

console.log(a2, a3);

As for your code, use this:

window["a"+i] = $('[name="answer['+i+']"]:checked').val();

In the for loop

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44