質問

Here are the two lines:

pixels[x-left] = {};
pixels[x-left][y] = true;

It would greatly allow me to clean up some code if the two could be combined into a single expression.

My first attempt looked something like this:

pixels[x-left] = { y: true };

However the letter y is being used as the index instead of the value of y, which is not OK.

役に立ちましたか?

解決

I'll start right off saying that Bergi's solution should be preferred, but in case you don't mind killing your code's readability:

(pixels[x-left] = {})[y] = true;

Fiddle

This works as an assignment expression returns the assigned value (in this case, a reference to the assigned object).

他のヒント

No, there is not no clean one*. Any property name in an object literal is interpreted literally.

One way out would be some kind of helper function, like

Object.set = function(o, p, v) { o[p] = v; return o; };

pixels[x-left] = Object.set({}, y, true);

but then everybody reading your code would need to know about Object.set.

* After @Fabricio's answer I can't state "no possibility" any more :-)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top