current position:Home>Common special characters in JS and TS

Common special characters in JS and TS

2022-06-24 12:40:08Star River dream~

JS Special operators

Chain judgment operator ( Safety navigator , Optional chain )(?.)

var res = {
console.log(res && &&;  //undefined
// Determine whether the underlying object of the attribute exists , The above wording is OK , But once too many properties are read , It's cumbersome to write .
console.log(res ?. data ?. name ) ;  //undefined

principle : Judge whether the object on the left is null or undefined, If so, go back undefined
res?.data amount to :res == null ? undefined :

<img [src]="pictureDatas[0]?.pictureUrl" useImg [spinner]="true"></img>

If pictureDatas[0] Valuable pictureUrl, It will be taken inside pictureUrl.
If pictureDatas[0] by null or undefined, There will be no error when the page rendering is loaded .

Null judgment operator (??)

console.log(value ? value : ‘ Null value ’)  // ’ ’ and 0 It will be empty 
console.log(value ?? ‘ Null value ’)
let a = '';
console.log(a ?? ' empty ')  // ''

Only the value to the left of the operator is null or undefined when , To return the value on the right . Otherwise, return the value on the left .

TS Special operators

Non empty assertion operators (!.)

It can be used to assert whether the operation object is right or not null He Fei undefined type .

console.log(config!.name)   //name
 If name stay config There must be something in it , that ts You can't report an error .

Optional parameters (?: )

stay ts in , It can put a Property is declared as optional Of .( Optional parameters and default parameters must be declared after the required parameters .)

Interface Person {
	id: number;
	name: string;
	age?: number;   // Optional attribute 

Null judgment operator (??)

Same as JS

Forced conversion to bool value (!!)

!! yes Force the expression to bool value Arithmetic , The result of operation is true or false, What is the value of an expression , The result is the corresponding bool value , No longer like ! Take the .

       // amount to if(a!=null && typeof(a)!=undefined && a!=’’)
	//a Code that is executed only when there is content ... 
!!false=false;    // it is to be noted that false and “false”  The difference between 
!!(NaN || undefined || null || 0 || ' ')=false;
var o={
    flag:true}; var test=!!o.flag;// Equivalent to var test=o.flag||false; alert(test);

copyright notice
author[Star River dream~],Please bring the original link to reprint, thank you.

Random recommended