Convert a JavaScript statement to a string

Viewed 72

I have an array in a variable like:

arr = [1, 2, 3]

How can I convert that statement to a string that it will be:

newArr = "arr = [1, 2, 3]"

6 Answers

If you mean it literally, you can do:

const infoArray = [1, 2, 3];
const newArray = `infoArray = [` + infoArray.join(',') + "]";

You can try this:

const arr = [1,2,3];
const newArr = `arr = [${arr.toString()}]`;
console.log(newArr);

//And A more Dynamic  Solution would be:

console.log(`${Object.keys({arr})} = [${arr.toString()}]`);

newArr = "arr = [" + String(arr) + "]"

You can write it as a function then call the only function by declaration.

const temp =  () => {
  arr = [1, 2, 3]
}
const src = temp.toString()
newArr = src.slice(9, src.length).slice(0, src.length - 1)

Above codes result on .toString() '() => {\n arr = [1,2,3]}' then we use .slice to cut out not needed parts.

Related