创建多个具有相同值的索引 - 简写
我正在寻找一种方法来最小化数组的创建,其中所有索引都具有相同的值。这可能不可能,但我会发现它非常方便。
考虑:(
var layer = [];
layer['game'] = new Kinetic.Layer();
layer['navigation'] = new Kinetic.Layer();
layer['notification'] = new Kinetic.Layer();
其中 Kinetic.Layer 是一个对象,但我怀疑这并不重要)
寻找类似的东西:
var layer['game','navigation','notification'] = new Kinetic.Layer();
这可能吗?当然,它并不是真正需要的 - 但我发现它非常方便,重复代码是一种不好的做法。
不,我不能有一个索引或变量,因为这些对象稍后会在我的代码中更改 - 并且必须在使用之前声明它们。
I'm looking for a way to minimize the creation of an array where all indexes would have the same value. It might not be possible, but I would find it very handy.
Consider:
var layer = [];
layer['game'] = new Kinetic.Layer();
layer['navigation'] = new Kinetic.Layer();
layer['notification'] = new Kinetic.Layer();
(where Kinetic.Layer is an object, however I suspect that it doesn't matter)
Looking for something like:
var layer['game','navigation','notification'] = new Kinetic.Layer();
Is this even possible? It, of course, isn't truly needed - but i would find it very handy, repeating code is kinda a bad practice.
And no, I can't have one single index or variable, as theese objects will change later in my code - and they have to be declared before usage.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,简写不会相同,因为所有三个层都指向相同的
Kinetic.Layer
而不是具有三个不同的层。因此,就您而言,请勿尝试速记。
然而,一般来说,您可以将相同的值分配给多个变量,如下所示:
旁注:您正在使用数组对象
[]
,然后分配字符串键 - 这并不严格正确,并且您应该改用通用对象{}
。In this case a shorthand would NOT be the same, as all three would point to the same
Kinetic.Layer
instead of having three different Layers.So, in your case, do NOT attempt a shorthand.
However in general, you can assign the same value to several variables like this:
Side-note: You're using an array object
[]
and then assigning string keys - this isn't strictly correct, and you should be using a generic object{}
instead.我很确定这应该有效,不记得我在哪里看到过它,但我在某个地方看到过它。
I'm pretty sure this should work, can't remember where I've seen it but I've seen it kicking around somewhere.