gpt4 book ai didi

javascript - 默认参数与问号

转载 作者:行者123 更新时间:2023-11-30 13:56:50 26 4
gpt4 key购买 nike

哪种处理可选输入参数的方法更好?

@Input() public isActive?: boolean;

@Input() public isActive: boolean = undefined;

还有一点困惑,下面代码的结果是什么,为什么(如果在 View 中未指定 isActive)?

@Input() public isActive?: boolean = undefined;

<app-sth [otherParameter]="true"></app-sth>

最佳答案

Which is better way for handling optional input parameters?

@Input() public isActive?: boolean@Input() public isActive: boolean = undefined 这两个语句之间没有区别。

两者都未定义

取自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined#Description :

A variable that has not been assigned a value is of type undefined.

第一条语句没有赋值,所以它是未定义的。第二个语句被分配了一个未定义的类型,因此它是未定义的。

附带说明,即使您将 null 的值分配给该属性,例如@Input() public isActive: boolean = null;,JS 引擎不会将该属性评估为 false。因为 null 既不是真也不是假。

如果你对 null 和 undefined 之间的区别感到好奇,你可以在这里阅读:What is the difference between null and undefined in JavaScript?


And also a little puzzle, what would be a result of below code and why (if in the view isActive is not specified)?

没有,不会抛出任何错误,因为您已将该属性声明为“可选”,如果您来自其他语言,您可能知道它是“可空的”。

关于javascript - 默认参数与问号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57111416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com