JavaScript驚くべき演算子
9751 ワード
JavaScript驚くべき演算子
皆さんこんにちは.
このチュートリアルでは、初心者の開発者のほとんどが知っている非常に便利で時間を節約する演算子について3つの驚くべき演算子を議論するつもりです.
3演算子は
1 .偽合体演算子(??)
syntax:
a??b
- If a is defined then the output will be a
- if a is not defined/ Nullish (NULL or UNDEFINED) then the output will be b
In other words, Nullish Coalescing Operator(??) returns the first argument if it is NOT null or undefined. Otherwise returns second argument
Examples:
let a=NULL console.log(a??50) //50 console.log(a) //NULL
let a=10 let c=30 console.log(a??b??c??d) //10 //gives output, the first defined value
2 .論理ヌル割り当て(??=)
syntax:
a ??= b
the above syntax is equivalent to a ?? (a=b)
- if a is not NULLISH (Null or Undefined), then output will be a
- if a is NULLISH, then output will be b, and value of b is assigned to a
example:
let a=NULL console.log(a??=50) //50 console.log(a) //50 //compare the output of a from the previous example.
3 .任意の連鎖演算子(?)
syntax:
obj ?. prop
- is similar to obj.prop if the value of obj exist,
- otherwise, if value of obj is undefined or null it returns undefined.
By using ?. operator with object instead of using only dot (.) operator , JavaScript knows to implicitly check to be sure that that obj is not null or undefined before attempting to access obj.prop
NOTE: obj can be nested as well like obj . name ?. firstnameexample:
let obj= { person:{ firstName:"John", lastName:"Doe" }, occupation: { compony:'capscode', position:'developer' }, fullName: function(){ console.log("Full Name is: "+ this.person.firstName+" >"+this.person.lastName) } } console.log(obj . person . firstName) //John console.log(obj . human . award) //TypeError: Cannot read property 'award' of undefined console.log(obj ?. human . award) //TypeError: Cannot read property 'award' of undefined console.log(obj . human ?. award) //undefined delete obj?.firstName; // delete obj.firstName if obj exists obj . fullName ?. () //logs John Doe obj ?. fullName() //logs John Doe obj . fullDetails() // TypeError: obj.fullDetails is not a function obj ?. fullDetails() // TypeError: obj.fullDetails is not a function obj.fullDetails ?. () //undefined
summing up these,
The optional chaining?.
syntax has three forms:
obj?.prop
– returnsobj.prop
ifobj
exists, otherwiseundefined
.obj?.[prop]
– returnsobj[prop]
ifobj
exists, otherwiseundefined
.obj.method?.()
– callsobj.method()
ifobj.method
exists, otherwise returnsundefined
.
このようなすべての希望とこのポストは有益であり、あなたの次のプロジェクトに役立つ.
任意のクエリや疑問がある場合は、私たちに連絡して自由に落ちた.
詳細についてはhttps://www.capscode.in/#/をご覧ください
or
Instagramで我々について来てください
私の記事があなたを助けたなら
ありがとう.
capscode
Reference
この問題について(JavaScript驚くべき演算子), 我々は、より多くの情報をここで見つけました https://dev.to/capscode/javascript-amazing-operators-366gテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol