[英]Can you change the same property for more than one variable with one line of code in Javascript?
例如,如果我有許多具有相同屬性x
變量,
a.x
b.x
c.x
我可以一次更改所有這些變量的x
值嗎? 就像是:
*.x = 200; // Change the value of "x" in every variable that has a property "x" to 200.
是否可以? 如果是這樣,如何?
如果您將變量收集在一個公共對象中,如下所示:
var points = { a: { x: 1, y: 2}, b: { x: 3, y: 4 }, c: {x: 5, y, 6 }
那么它幾乎可以完成(減去整潔的通配符符號)。 這是一個應該適合您需要的功能:
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;
}
}
}
用法:
setPropertyForAll(points, "x", 42);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.