Home > Software engineering >  JavaScript cannot insert variable value
JavaScript cannot insert variable value

Time:04-23

I'm trying to insert the value of the variable newData123 into the test attribute.

But it inserts the variable name newData123 instead of its value 456...

What am I doing wrong?

Edited

The reason why I don't directly use elm.setAttribute('test', 'newData123'); is that I need to pull the data dynamatically from another script like the below:

const newData123 = '456',
   newData456 = '789';

And that is why I need to use the template literal here in a programmatic way instead of hard code it.

const elm = document.querySelector('.test'),
  data = '123',
  newData123 = '456';
  
elm.setAttribute('test', `newData${data}`);

const check = elm.getAttribute('test');

console.log(check);
<p ></p>

CodePudding user response:

It would be much safer if you formatted all your newData variables into an object of some sort.

const data_obj = {
  newData123: '456',
  newData456: '123'
}
const data = '123'
console.log(data_obj[`newData${data}`]) // 456

const data2 = '456'
console.log(data_obj[`newData${data2}`]) // 123

Since JS is a little fuzzy with datatypes, you could even do something like this, which would require minimal refactoring:

const newData = {
  123: '456',
  456: '123'
}
let data = '123'
console.log(newData[data]) // 456

data = '456'
console.log(newData[data]) // 123
  
console.log(newData[123]) // 456

CodePudding user response:

The actual problem is since you have newData${data} it will concatenate the two strings and the final output will be, newData123.

To fix this issue, you can use eval() function here, but it's not the safest option.

Solution:

const elm = document.querySelector('.test'),
data = '123',
newData123 = '456';
elm.setAttribute('test', eval(`newData${data}`));
    
const check = elm.getAttribute('test');
    
console.log(check);
<p ></p>

  • Related