简体   繁体   中英

Ternary Operator

I recently started learning Ternary Operator. However I am stuck in this specific one. In JavaScript language, I want to check if a student is a member of the library, if the student is, it has to print "You are a member!" if not, it has to print "Not found!". To check, we can use the student id for the validation of the library membership.

It would be easier for me to tailor my answer to your need if I had some code to work with. But basically, you can use something as simple as:

studentIsMember ? 'You are a member' : 'Not found!'

This will print 'You are a member' if studentIsMember is true and 'Not Found' if false.

If you need to lookup students in a members list using their id, you can have something like:

members.includes(student.id) ? 'You are a member' : 'Not found!'

this will look into the members array which holds an array of all members IDs and see if the specific student id is in that array.

Lastly, if you have to do more operations to validate a student's membership status, you can write a function that does the operations and returns true or false depending on whether the student is a member or not, and then use the ternary operator like this:

studentIsMember(student.id) ? 'You are a member' : 'Not found!'

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM