简体   繁体   English

我怎样才能实现类似于 javascript 中的字符串指针的东西?

[英]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? 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)

Javascript does not have pointers. Javascript 没有指针。

But you can wrap a value in an object and pass references to that object around.但是您可以将一个值包装在 object 中,然后传递对该 object 的引用。

 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.这可能是您最接近这种行为的地方。

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使console.log(s1)显示其他内容的唯一方法是使用一行代码

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:我想您可以将字符串放入数组或 object 中,然后检查它:

 const strings = { s1: 'hi', s2: 'bye', }; for (const [key, str] of Object.entries(strings)) { if (str.length < 3) { strings[key] += '*'; } } console.log(strings.s1);

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] =它使用 ES6 中的新事物,您可以在其中分配事物[s1, s2] =

let s1 = "hi", s2 = "bye";
[s1, s2] = [s1, s2].map(s => s + (s.length < 3 ? "*" : ""));

In javascript there is no "pointers", and the only way access local variables is through evil function the eval() :在 javascript 中没有“指针”,访问局部变量的唯一方法是通过邪恶的 function 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); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM