Javascript / Coffeescript:如何优雅地对多个变量运行函数(并修改它们)?
我将编写 Coffeescript,但生成的 javacript 应该很明显 我想对许多变量运行一个函数,并且想保留它们的结果,因为它们是在其他地方读取的对象的属性。 因为 Javascript 似乎会将它们作为值而不是引用,所以我只找到了这种丑陋的方法来实现我想要的:
[@au, @iu, @rdis, @rtres, @rmin, @rmax, @dmil, @dal, @dacc] =
[@au, @iu, @rdis, @rtres, @rmin, @rmax, @dmil, @dal, @dacc].map (x) -> x * (0.95 + Math.random()*0.1)
没有更好的方法吗?
I will write Coffeescript but the javacript generated should e evident
I want to run a function on many variables and I want to keep the result on them, as they are properties of the object that are read somewhere else.
As it seems that Javascript will put them as value and not reference, I have only found this ugly way to implement what I want:
[@au, @iu, @rdis, @rtres, @rmin, @rmax, @dmil, @dal, @dacc] =
[@au, @iu, @rdis, @rtres, @rmin, @rmax, @dmil, @dal, @dacc].map (x) -> x * (0.95 + Math.random()*0.1)
There is no better way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种方法可能是:
或者,您可以将这些值的对象组合到您的类中:
One way might be:
Alternatively, you could instead compose an object of those values into your class:
正如 Ricardo Tomasi 所说,问题在于您想要就地修改多个值。这就需要要么重复自己,要么像卢西安建议的那样,使用字符串而不是标识符。
我建议将您的状态存储在比简单对象更复杂的结构中。如果将每个值放入其自己的对象包装器中,例如
,那么您可以简单地编写“
您可能将来决定在这些对象中存储其他状态”。例如,如果您想查看将来的随机值是什么,您可以将迭代器更改为
您可能还想考虑使用事件模型(如 Backbone.js 中的模型)而不是简单对象。
The problem is, as Ricardo Tomasi said, that you want to modify several values in-place. That necessitates either repeating yourself or, as Lucian suggests, using strings rather than identifiers.
What I'd recommend is storing your state in a more sophisticated structure than a simple object. If you put each value in its own object wrapper, e.g.
then you could simply write
You might in the future decide to store additional state in these objects. For instance, if you want to see what the random value was in the future, you could change the iterator to
You might also want to think about using evented models (like those in Backbone.js) rather than simple objects.
我想我会这样处理:
如果我经常以不同的方式破坏同一组值,我可能会将它们分成自己的集合,如下所示:
这可能会使意图更清晰,并且在做很多事情的函数中,为了简洁起见,对它进行本地引用只是一个很小的强加,即:
I think I'd go about it like so:
If I was going to mangle the same set of values in different ways very often, I'd probably split them out into their own collection as so:
That might make the intent clearer, and in functions that do a lot of stuff, it'd be only a minor imposition to make a local reference to it for brevity, i.e.: