skip to Main Content

I am trying to set each item in an array into their own variables. Here is what the array looks like:

labels = ["label1", "label2", "label3", "label4", "label5"]

I have already created the variables:

let name1;
let name2;
let name3;
let name4;
let name5;

So I want to set each array item to each variable so that they look like this:

let name1 = "label1";
let name2 = "label2";
let name3 = "label3";
let name4 = "label4";
let name5 = "label5";

I am not really sure with how to proceed with this.

2

Answers


  1. Is this what you want?

               const labels = ["label1", "label2", "label3", "label4", "label5"]
    
               var name1 = labels[0];
               var name2 = labels[1];
               var name3 = labels[2];
               var name4 = labels[3];
               var name5 = labels[4];
    
               console.log('name1=' + name1);
               console.log('name5=' + name5);
    Login or Signup to reply.
  2. Here is one way to do it:

    const labels = ["label1", "label2", "label3", "label4", "label5"];
    
    const [name1, name2, name3, name4, name5] = labels;
    
    console.log('name1=' + name1);
    console.log('name5=' + name5);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search