之间的确切区别是什么?和?:角运算符 [英] What is the exact difference between ?. and ?: operators in angular
问题描述
我没有考虑?:(三元运算符).有时我在YouTube教程中观看人们在HTML页面中使用?.运算符,有时他们在TS(打字稿)页面中使用?:的情况.我不清楚它们到底有什么不同?
I am not thinking about ?:(ternary operator). Sometimes I am watching in YouTube tutorials where people are using ?. Operator in HTML pages, and sometimes they are using ?: in TS(typescript) pages. I am not so clear how exactly they are different?
推荐答案
所以使用?有区别吗?在Angular中,您可能会参考这三种用法.
So there is a difference when using the ? within Angular, here are the three ways you may be referring to for the usage.
安全操作员
在HTML中设置带有问号的值时,这是安全的检查,因此在访问变量之前先检查其是否已定义. (尝试使用不存在的访问值将导致错误).
When you set a value within the HTML with a question mark in it, this is a safe check, so you check the variable is defined before you access it. (trying at access values the do not exist will result in errors).
下面的代码段将在检查文本之前检查this.example
是否具有值,这将导致错误.如果在未定义的情况下访问文本,则几乎可以确保不需要的行为.
The snippet below would check this.example
has a value before checking for text which would result in an error. If text is accessed while undefined this can almost assure unwanted behavior.
<p>{{example?.text}}</p>
这可以确保一切安全,以阅读有关安全操作员的更多信息,通读Angular文档
This keeps everything safe, to read more about safe operators, have a read through the Angular docs found here
可选参数
我认为您正在寻找的下一个用途是函数/接口中的可选值.这意味着如果在没有exampleValue
的情况下调用该接口,则不会引发错误,因为现在已将其定义为可选.
The next use which is what I think you were looking for is optional values in functions / interface. This means that the interface will not throw an error if it is called without the exampleValue
as it has now been defined as optional.
export interface Itest
{
exampleValue?: string; // optional
neededValue: string; // non-optional
}
或者在函数内,如果没有可选的指示符(?
),则调用函数时将发生错误. this.exampleFunction();
Or within a function, without the optional indicator (?
) an error would occur if the function was called like. 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.
}
有关此示例的更多示例,请参见有关可选参数
More examples of this can be found in this short article about Optional Parameters
条件(三元)运算符
问题不是要查找此问题,而是认为将其弹出是另一种可以使用?
的情况.
The question was not looking for this but thought it would make sense to pop it in as its another case where the ?
can be seen in use.
在打字稿中看到时,您可以在条件三元语句(if / else)
中使用它.
When seen in typescript you can use it in a conditional ternary statement (if / else)
looking like so.
const example = 'hello';
console.log(example === 'hello' ? 'im true' : 'im false');
这与编写以下语句相同.
which would be the same as writing the following statement.
const example = "hello";
if (example === 'hello')
{
console.log('im true');
}else
{
console.log('im false');
}
More information and uses of the Conditional (ternary) operator can be found here.
这篇关于之间的确切区别是什么?和?:角运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!