[英]If statement within javascript variable declaration
I have such variable declaration in my JavaScript method on : 我的JavaScript方法中有这样的变量声明:
var MyVariable = {
CarMake: "Lexus",
CarColor: "Black"
}
What I am trying to accomplish is to add some login within MyVariable declaration such as: 我要完成的工作是在MyVariable声明中添加一些登录信息,例如:
var MyVariable = {
CarMake: "Lexus",
if (carType == "sedan") {
NumberOfDoors: 4,
}
CarColor: "Black"
}
Is this possible somehow? 这有可能吗?
With a one-line object you can't do it. 对于单行对象,您将无法做到。 You need to assign it later.
您需要稍后分配。 But I thnik you can create a
class(ES6)
and use like 但是我想你可以创建一个
class(ES6)
并使用像
class Car{ constructor(maker, color, type){ this.maker = maker; this.color = color; if(type === 'sedan'){ this.numberOfDoors = 4; } } } var car = new Car('Lexus','Black','sedan'); console.log(car.numberOfDoors);
Or use the function
syntax 或使用
function
语法
function Car(maker, color, type){ this.maker = maker; this.color = color; if(type === 'sedan'){ this.numberOfDoors = 4; } } var car = new Car('Lexus','Black','sedan'); console.log(car.numberOfDoors);
I suppose you could do 我想你可以做
var MyVariable = {
CarMake: "Lexus",
CarColor: "Black",
NumberOfDoors: (carType === 'sedan') ? 4 : undefined
}
which is not exactly the same, but close. 这并不完全相同,但是很接近。
But how about 但是怎么样
var MyVariable = {
CarMake: "Lexus",
CarColor: "Black"
}
if (carType === 'sedan') {
MyVariable.NumberOfDoors = 4
}
You could wrap this into a "factory" function and then do 您可以将其包装到“工厂”函数中,然后执行
var MyVariable = makeCar("Lexus", "Black", "sedan")
You need to create your variable before and add the new attribute after : 您需要在之前创建变量,并在之后添加新属性:
var MyVariable = {
CarMake: "Lexus",
CarColor: "Black"
}
if (carType == "sedan") {
MyVariable.NumberOfDoors = 4
}
One way you could do this: 您可以这样做的一种方式:
var MyVariable = {
CarMake: "Lexus",
CarColor: "Black"
}
if (carType == "sedan") {
MyVariable.NumberOfDoors = 4;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.