gpt4 book ai didi

angular - 之间的确切区别是什么?和 ? : operators in angular

转载 作者:太空狗 更新时间:2023-10-29 17:45:57 26 4
gpt4 key购买 nike

我没有考虑 ?:(三元运算符)。有时我在 YouTube 教程中看到人们在 HTML 页面中使用 ?. 运算符,有时他们在 TS(typescript) 页面中使用 ?:。我不太清楚它们到底有什么不同?

最佳答案

所以在使用 ?在 Angular 中,您可以引用以下三种用法。

安全运算符(operator)

当您在 HTML 中设置一个带有问号的值时,这是一种安全检查,因此您在访问变量之前检查该变量是否已定义。 (尝试访问不存在的值将导致错误)。

下面的代码片段会检查 this.example 是否有值,然后再检查会导致错误的文本。如果在未定义的情况下访问文本,这几乎可以确保出现不需要的行为。

<p>{{example?.text}}</p>

这可以保证一切安全,要阅读更多关于安全运算符的信息,请阅读 Angular 文档 found here

可选参数

我认为您正在寻找的下一个用途是函数/接口(interface)中的可选值。这意味着如果在没有 exampleValue 的情况下调用接口(interface)将不会引发错误,因为它现在已定义为可选。

export interface Itest
{
exampleValue?: string; // optional
neededValue: string; // non-optional
}

或者在一个函数中,如果没有可选的指示符(?),如果函数被调用时会发生错误。 this.exampleFunction();

public exampleFunction(test?): void 
{
console.log(test);
// this function can be called with or without test being passed in without causing an error.
}

有关这方面的更多示例可以在这篇关于 Optional Parameters 的短文中找到

条件(三元)运算符

问题不是在寻找这个,而是认为将它弹出作为另一种情况是有意义的,在这种情况下可以看到正在使用 ?

当在 typescript 中看到时,您可以在条件三元语句 (if/else) 中使用它,看起来像这样。

const example = 'hello';
console.log(example === 'hello' ? 'im true' : 'im false');

这与编写以下语句相同。

    const example = "hello";

if (example === 'hello')
{
console.log('im true');
}else
{
console.log('im false');
}

有关条件(三元)运算符的更多信息和用法,请参见 here.

关于angular - 之间的确切区别是什么?和 ? : operators in angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815790/

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