-2

If I have many variables with the same property x, for example,

a.x
b.x
c.x

Can I change the value of x for all these variables at one time? Something like:

*.x = 200; // Change the value of "x" in every variable that has a property "x" to 200.

Is it possible? And if so, how?

metacubed
  • 6,481
  • 5
  • 31
  • 61

2 Answers2

0

No. You can't set multiple variables of the same type at once using a wildcard like you propose.

You can concatenate statements though like this:

left.x = right.x = 200;

Or use a list or dictionary like object in javascript and iterate over every key that matches.

Community
  • 1
  • 1
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
0

If you gather your variables inside a common object like so:

var points = { a: { x: 1, y: 2}, b: { x: 3, y: 4 }, c: {x: 5, y, 6 }

then it can almost be done (minus the neat wildcard notation). Here's a function that should fit your need:

function setPropertyForAll(container, propName, newValue) {
    for (var key in container) {
        if (container.hasOwnProperty(key) && container[key] !== null && container[key].hasOwnProperty(propName)) {
            container[key][propName] = newValue;
        }
    }
}

Usage:

setPropertyForAll(points, "x", 42);