1). eval()
2). Window object
Examples:-
i want to create apple, banana and orange named variables or etc.
Using eval():-
<script>
let obj1 = ['apple', 'banana', 'orange'];
for (let i = 0; i < obj1.length; i++) {
//console.log(obj1[i])
eval(`let ${obj1[i]} = ${i}`)
}
console.log(apple) //Output: 0
console.log(banana) //Output: 1
console.log(orange) //Output: 2
</script>
Using Window object:-
using this method we create a global variable.
<script>
let obj1 = ['apple', 'banana', 'orange'];
for (let i = 0; i < obj1.length; i++) {
//console.log(obj1[i])
window[`${obj1[i]}`] = i
}
console.log(apple) //Output: 0
console.log(banana) //Output: 1
console.log(orange) //Output: 2
</script>
Tags:
javascript
useful inforamtion we want more such like this
ReplyDelete