'How can I achieve something similar to a pointer to a string in javascript?
Is there a concept like a pointer to a string in javascript? Or how would this be done?
let s1 = "hi";
let s2 = "bye";
// I want to write my code like this [,].forEach();
// This is the bit where I want s1 and s2 in the [,] array to actually be pointers to a string
[s1,s2].forEach(s => {if(s.length < 3) s += "*";});
// I want console.log(s1) === "hi*"
// I want console.log(s2) === "bye" (unchanged)
Solution 1:[1]
Javascript does not have pointers.
But you can wrap a value in an object and pass references to that object around.
let s1 = { value: "hi" };
let s2 = { value: "bye" };
[s1,s2].forEach(s => {
if(s.value.length < 3) s.value += "*";
});
console.log(s1.value)
console.log(s2.value)
That's probably the closest you're going to get to this behaviour.
Solution 2:[2]
You cannot reassign individual identifiers unless you specifically reference the identifier. So given
let s1 = "hi";
The only way to make console.log(s1)
show something else would be to have a line of code that does
s1 = // something else
And strings are immutable, of course - for a string, you'd have to reassign it, since you can't mutate it.
I suppose you could put the strings into an array or an object, then examine that instead:
const strings = {
s1: 'hi',
s2: 'bye',
};
for (const [key, str] of Object.entries(strings)) {
if (str.length < 3) {
strings[key] += '*';
}
}
console.log(strings.s1);
Solution 3:[3]
I think I found a solution myself.
Could anyone comment if this is good practice or not?
It uses the new thing in ES6 where you can assign things [s1, s2] =
let s1 = "hi", s2 = "bye";
[s1, s2] = [s1, s2].map(s => s + (s.length < 3 ? "*" : ""));
Solution 4:[4]
In javascript there is no "pointers", and the only way access local variables is through evil function the eval()
:
{
let s1 = "hi";
let s2 = "bye";
["s1","s1"].forEach(s => {
let n = eval(s);
if (n.length < 3)
eval(s + ' += "*"');
});
console.log(s1,s2);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alex Wayne |
Solution 2 | CertainPerformance |
Solution 3 | Rewind |
Solution 4 |