Javascript中左侧的可选链接
是否可以在Javascript中使用赋值左侧的运算符Javascript中左侧的可选链接,javascript,typescript,Javascript,Typescript,是否可以在Javascript中使用赋值左侧的运算符= const building={} 建筑物?楼层?公寓?数量=3;//这可能吗? 我曾在Chrome Canary上尝试过此功能(因为),但没有成功: 不,这是不可能的。 报告明确指出 可选的链接运算符?。允许读取 位于连接对象链深处的属性,没有 必须明确验证链中的每个引用 有效 对不起,这是不可能的 为了得到一个规范的答案:MDN文档对此并不明确,但您可以阅读以了解更多信息。它: 以下内容不受支持,尽管它有一些用例;有关讨论,请参阅:
=
const building={}
建筑物?楼层?公寓?数量=3;//这可能吗?
我曾在Chrome Canary上尝试过此功能(因为),但没有成功:
不,这是不可能的。 报告明确指出 可选的链接运算符?。允许读取 位于连接对象链深处的属性,没有 必须明确验证链中的每个引用 有效
对不起,这是不可能的 为了得到一个规范的答案:MDN文档对此并不明确,但您可以阅读以了解更多信息。它: 以下内容不受支持,尽管它有一些用例;有关讨论,请参阅:
- 可选属性分配:
a?.b=c
希望有帮助;祝你好运 我一直在研究这个问题,遗憾的是,正如其他评论者已经指出的那样,在撰写本文时,通过可选链接进行赋值在typescript中似乎是不可能的,并且确实会给您带来解析器警告: 赋值表达式的左侧不能是可选的属性访问 当尝试类似于:
class A{
b?: string;
}
var a = new A();
a?.b = "foo";
但是,由于可选赋值有时很有用,因此仍然有使用单行if查询的老式方法,如:
class A{
b?: string;
}
try{a.b = "foo0"} // throws TypeError
catch(e){console.log(e.toString())} // a is undefined
if(a) a.b = "foo1"; // skips
console.log(a); // a is undefined
var a: any;
if(a) a.b = "foo2"; // skips
console.log(a); // a is undefined
a = null;
if(a) a.b = "foo3"; // skips
console.log(a); // a is null
a = undefined;
if(a) a.b = "foo4"; // skips
console.log(a); // a is undefined
a = new A();
if(a) a.b = "foo5"; // runs
console.log(a); // a is A: {"b": "foo5"}
if(null) console.log("bar0"); // skips
if(undefined) console.log("bar1"); // skips
if({}) console.log("bar2"); // runs
if({something: "there"}) console.log("bar3"); // runs
if([]) console.log("bar4"); // runs
if(["not empty"]) console.log("bar5"); // runs
为了演示一个实际可行的示例,下面是一个kotlin片段:
class A{
var b: B? = null;
var title: String? = null;
override fun toString():String = "Instance of class A with title: ${this.title} and b of value: ${this.b.toString()}";
}
class B{
var title: String? = null;
override fun toString():String = "Instance of class B with title: ${this.title}";
}
fun main() {
var a:A? = null;
println(a); // null
try{a!!.title = "foo0"} catch(e:Exception){println(e)} // NPE
a?.title = "foo1";
println(a); // null
a = A();
println(a); // Instance of class A with title: null and b of value: null
a?.title = "foo2";
println(a); // Instance of class A with title: foo2 and b of value: null
try{a!!.b!!.title = "bar0"} catch(e:Exception){println(e)} // NPE
a?.b?.title = "bar1";
println(a); // Instance of class A with title: foo2 and b of value: null
a?.b = B();
println(a); // Instance of class A with title: foo2 and b of value: Instance of class B with title: null
a?.b?.title = "bar2";
println(a); // Instance of class A with title: foo2 and b of value: Instance of class B with title: bar2
a?.b?.let{it.title = "bar3"}
println(a); // Instance of class A with title: foo2 and b of value: Instance of class B with title: bar3
}
现在我并不是说一种语言比另一种更好,而是说目的和理念需要不同的设计选择,并决定最终任何编程或脚本语言所使用的工具的最终形状。
虽然我也有点恼火,因为我不能在typescript中为可选链接赋值
编辑:我使用了这些游乐场网站来测试这些东西: