
文章目录
事情是这样的
今天写页面,想显示个协议类型,写了个函数:
javascript
const getProtocol = () => {
if (type == 1) return "协议A";
if (type == 2) return "协议B";
if (type == 3) return "协议C";
};
然后页面上这么用:
html
<span>协议类型:{getProtocol}</span>
结果页面出来这么个玩意:
协议类型:() => { if (type == 1) return "协议A"; if (type == 2) return "协议B"; if (type == 3) return "协议C"; }
问题出在哪
忘了加括号。
getProtocol 是函数本身,getProtocol() 才是调用它。
我写的是 {getProtocol},等于把整个函数的源码扔页面上了。
改成 {getProtocol()} 就好了。
顺便修了另外两个坑
原来的代码还有两个隐患:
1. 没考虑空值
万一 type 不存在,函数就返回 undefined,页面显示空白。
加了个默认值:
javascript
const getProtocol = () => {
if (type == 1) return "协议A";
if (type == 2) return "协议B";
if (type == 3) return "协议C";
return "未知协议"; // 兜底
};
2. 数据取法不安全
原代码写了 items!.protocolType,要是 items 是空的直接就崩了。
改成 items?.protocolType,安全一点。
最终代码
javascript
const getProtocol = () => {
const type = data?.form?.items?.protocolType;
if (type === 1) return "协议A";
if (type === 2) return "协议B";
if (type === 3) return "协议C";
return "未知协议";
};
页面调用:
html
<span>协议类型:{getProtocol()}</span>
一个更清爽的写法
其实这种映射关系,用对象比 if 好看:
javascript
const getProtocol = () => {
const type = data?.form?.items?.protocolType;
const map = {
1: "协议A",
2: "协议B",
3: "协议C"
};
return map[type] || "未知协议";
};
您好,我是肥晨。
欢迎关注我获取前端/AI学习资源,日常分享技术变革,生存法则;行业内幕,洞察先机。