This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.
In python I can do this:
arr = ['one', 'two']
one, two = arr
how do I do that in JavaScript?
This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.
In python I can do this:
arr = ['one', 'two']
one, two = arr
how do I do that in JavaScript?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Here is an example. You can try like this.
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
My example works for your example but also if you dont know the array or the array length.
arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
var val = arr[i];
eval('var '+arr[i]+'= arr[i];');
}
Know you have 2 variables. The first is 'one' who is "one"and the second is 'two' who is "two". Your problem is solved! But for the code snippet, i created extra elements to display the var's and i logged it.
arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
var val = arr[i];
eval('var '+arr[i]+'= arr[i];');
}
var p = document.createElement("p");
p.innerHTML = one + " " + two;
document.body.appendChild(p);
console.log(one, two);
arr = ['one', 'two'];
var length = arr.length;
for (var i = 0; i < length; i++)
{
var val = arr[i];
eval('var '+arr[i]+'= arr[i];');
}
var p = document.createElement("p");
p.innerHTML = one + " " + two;
document.body.appendChild(p);
console.log(one, two);