You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript的Ternary Operator实现图书馆会员身份校验?

使用JavaScript三元运算符实现图书馆会员校验

基础实现示例

先定义图书馆会员ID集合,再通过三元运算符完成校验逻辑:

// 模拟图书馆会员ID列表
const memberIds = ['S1001', 'S1002', 'S1003', 'S1004'];
// 待校验的学生ID
const targetStudentId = 'S1002';

// 三元运算符核心判断逻辑
const message = memberIds.includes(targetStudentId) 
  ? "You are a member!" 
  : "Not found!";

// 输出结果
console.log(message);

代码说明

  • 三元运算符的语法结构:条件表达式 ? 满足条件的返回值 : 不满足条件的返回值
  • 用Array.includes()方法判断目标ID是否在会员列表中,返回的布尔值作为三元判断的依据
  • 条件为true时输出会员提示,false时输出未找到提示

结合用户输入的场景

如果需要从用户输入获取学生ID,可调整为:

const memberIds = ['S1001', 'S1002', 'S1003'];
const inputId = prompt("Enter your student ID:");
const result = memberIds.includes(inputId) ? "You are a member!" : "Not found!";
alert(result);

内容的提问来源于stack exchange,提问作者Kurozi Gurung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:01:07