js筛选条件匹配对应值的几种方法

根据状态值筛选出对应的状态文字
switch写法:

function test (status) {
  switch (status) {
    case 0:
      return "未启动"
    case 1:
      return "执行中"
    case 2:
      return "停止"
    case 3:
      return "完成"
    default:
      return "取消"
  }
}

对象方法:

const statusTest  = {
  0: "未启动",
  1: "执行中",
  2: "停止",
  3: "完成"
}
function formatStatus(status) {
  return statusTest[status] || "取消"
}

使用Map方法:

const statusTest = new Map()
.set(0,"未启动")
.set(1,"执行中")
.set(2,"停止")
.set(3,"完成")
function formatStatus(status) {
  return statusTest.get(status) || "取消"
}

使用数组的filter方法:

const statusTest = [
    { value: 0, text: '未启动' }, 
    { value: 1, text: '执行中' }, 
    { value: 2, text: '停止' }, 
    { value: 3, text: '完成' },
    { value: 4, text: '取消' }
]
function formatStatus(status) {
  return statusTest.filter(f => f.value=== status)
}

还有一种但是只适用于值为数字的,取数组索引对应的值

const statusTest =["未启动","执行中","停止","完成","取消"]
const result = statusTest[status]

猜你喜欢

转载自blog.csdn.net/qq_36711388/article/details/89819269
今日推荐