我是初学者网络开发人员。 我英语不好,抱歉。
export class Vector{
protected x : number = 0
protected y : number = 0
protected z : number = 0
set(x?: number , y? : number , z? : number){
this.x = x ? x : this.x
this.y = y ? y : this.y
this.z = z ? z : this.z
}
}
我想从“this.x = x ? x : this.x”中删除“:this.x”
我想写一会儿,我想擦掉其他部分。
set(x?: number , y? : number , z? : number){
if(x){
this.x = x
}
}
我不想这样写。 因为它不酷。 任何人请告诉我编写这段代码的好方法。
--添加---
我想做的就是这样的事情。
set(x?: number , y? : number , z? : number){
this.x = x ? x : DO NOTHING(WRITE NOTHNG)
}
这里!平等之下! 说“;”是必需的。
最佳答案
通常 x && this.x=x
是完成此操作的最短语法。
但是 x、y 和 z 都是数字。使用这种数字简写语法有点危险。考虑使用 x=0 调用 set 的情况。 0 && this.x=x
不会执行 this.x,因为 0 在 Javascript 中是错误的。从阅读你的代码来看,这似乎不是你想要实现的目标,相反,你想在 x 未定义的情况下跳过设置 this.x 。
在这种情况下,我建议使用以下代码:
set(x?: number , y? : number , z? : number){
typeof x === 'number' && (this.x = x);
typeof y === 'number' && (this.y = y);
typeof z === 'number' && (this.z = z);
}
这样,您的 set
函数将支持发送 0 作为参数,但目前尚不支持。
关于javascript - TypeScript 简单写下 "if",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095532/