如果出于某种原因我想在对象中组合其他两个属性,我能够做到吗?
例如,如果我有:
Cars = {
myFirstCar = { model: "mazda", color: "grey" }
myCurrentCar = { model: "toyota", color: "black" }
}
并说我想在myFirstCar
内添加另一个属性,该属性将model
和color
组合在一起。像这样:
Cars = {
myFirstCar = { model: "mazda", color: "grey", conclusion: model + color }
myCurrentCar = { model: "toyota", color: "black" }
}
答案 0 :(得分:2)
除了代码中的其他语法错误之外,你不能完全这样做。相反,你做这样的事情:
set = a,b,c, ...
While(set not empty) {
Create newSet
Add set.first to new list
Remove set.first from set // this line isnt necessary if a curve doesnt intersect with self
For (i = 0 , i < newset.length , i++)
{
newSet.add(set.FindAll(x => _CurveLoopsIntersect(x, newSet[i]));
set.removeRange(newSet); // this line may have error that the first element doesnt exist in set
}
Add newSet to set of sets
其余代码无效。我不确定构造
myFirstCar = { model: "mazda", color: "grey" }
myFirstCar.conclusion = myFirstCar.model + myFirstCar.color;
应该实现。如果您尝试实例化对象,请使用Cars = {
a = b
c = d
}
代替:
。如果您需要数组,请使用=
代替[]
并删除变量名称和作业{}
。
答案 1 :(得分:0)
您可以使用ES6 computed property name syntax:
执行类似的操作
var cars = {
myFirstCar: { model: "mazda", color: "grey",
get conclusion() { return this.model + this.color } },
myCurrentCar: { model: "toyota", color: "black" }
}
console.log(cars.myFirstCar);
// Let's update the color, ... and print it again
cars.myFirstCar.color = 'orange';
console.log(cars.myFirstCar);
正如您在代码段中看到的,这是 live 属性:它跟随属性的更新。
但是如果你有多个汽车对象,那么为car对象使用构造函数可能会很有用,它定义了这个额外的属性:
function Car(model, color) {
this.model = model;
this.color = color;
Object.defineProperty(this, 'conclusion', {
get: function() { return this.model + this.color; },
enumerable: true
});
}
var cars = {
myFirstCar: new Car("mazda", "grey"),
myCurrentCar: new Car("toyota", "black")
}
console.log(cars.myFirstCar);
console.log(cars.myCurrentCar);