创建多个具有相同值的索引 - 简写

发布于 2025-01-03 00:44:12 字数 501 浏览 2 评论 0原文

我正在寻找一种方法来最小化数组的创建,其中所有索引都具有相同的值。这可能不可能,但我会发现它非常方便。

考虑:(

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白芷 2025-01-10 00:44:12

在这种情况下,简写不会相同,因为所有三个层都指向相同的 Kinetic.Layer 而不是具有三个不同的层。

因此,就您而言,请勿尝试速记。

然而,一般来说,您可以将相同的值分配给多个变量,如下所示:

layer['game'] = layer['navigation'] = layer['notification'] = value;

旁注:您正在使用数组对象 [],然后分配字符串键 - 这并不严格正确,并且您应该改用通用对象 {}

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:

layer['game'] = layer['navigation'] = layer['notification'] = value;

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.

白云不回头 2025-01-10 00:44:12

我很确定这应该有效,不记得我在哪里看到过它,但我在某个地方看到过它。

var layer = [];
layer['game'] = layer['navigation'] = layer['notification'] = new Kinetic.Layer();

I'm pretty sure this should work, can't remember where I've seen it but I've seen it kicking around somewhere.

var layer = [];
layer['game'] = layer['navigation'] = layer['notification'] = new Kinetic.Layer();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文