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]"
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]"
Try this:
const arr = [1, 2, 3];
const str = `${Object.keys({arr})} = ${JSON.stringify(arr)}`;
console.log(str);
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I would use this JSON.Stringify().
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
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()}]`);
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.