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

JavaScript中如何将数组数字转为对应字符串并使用If语句实现替换

JavaScript实现数组元素替换方案

方案1:映射对象 + Array.map()(推荐,易扩展)

这种方案耦合度低,后续如果新增替换规则只需要修改映射对象即可,不需要调整逻辑代码:

// 原数组
const arr = [1, 1, 2, 3]
// 定义数值和颜色的映射关系
const colorMap = {
  1: 'red',
  2: 'blue',
  3: 'white'
}
// 遍历替换,?? 运算符用于处理无匹配映射时保留原数值,避免出现undefined
const result = arr.map(item => colorMap[item] ?? item)

console.log(result) // 输出:['red', 'red', 'blue', 'white']

方案2:switch分支判断实现

如果替换规则固定且不会频繁变更,可以用switch分支判断实现:

const arr = [1, 1, 2, 3]
const result = arr.map(item => {
  switch (item) {
    case 1: return 'red'
    case 2: return 'blue'
    case 3: return 'white'
    default: return item
  }
})

console.log(result) // 输出:['red', 'red', 'blue', 'white']

方案3:直接修改原数组(不推荐,会污染原数据)

如果业务要求直接修改原数组,可以用Array.forEach遍历改写:

const arr = [1, 1, 2, 3]
const colorMap = { 1: 'red', 2: 'blue', 3: 'white' }
arr.forEach((val, index) => {
  arr[index] = colorMap[val] ?? val
})

console.log(arr) // 输出:['red', 'red', 'blue', 'white']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 08:36:04