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

如何在JavaScript中将数组里的"plus"替换为"+"?

JavaScript数组替换指定值的实现方法

以下几种方法可以帮你把数组中的"plus"替换为"+":

1. 使用map创建新数组(不修改原数组)

map方法会遍历数组并返回一个新数组,适合需要保留原数组的场景:

const originalArr = ['x', 'plus', 'y', 'plus', 'z'];
const updatedArr = originalArr.map(item => item === 'plus' ? '+' : item);
console.log(updatedArr); // 输出: ['x', '+', 'y', '+', 'z']

2. 使用forEach修改原数组

如果不需要保留原数组,forEach可以直接遍历并修改数组元素:

const arr = ['x', 'plus', 'y', 'plus', 'z'];
arr.forEach((item, idx) => {
  if (item === 'plus') {
    arr[idx] = '+';
  }
});
console.log(arr); // 输出: ['x', '+', 'y', '+', 'z']

3. 使用for循环(兼容性最优)

最基础的for循环,兼容所有JavaScript环境,适合需要兼容旧版浏览器的场景:

const arr = ['x', 'plus', 'y', 'plus', 'z'];
for (let i = 0; i < arr.length; i++) {
  if (arr[i] === 'plus') {
    arr[i] = '+';
  }
}
console.log(arr); // 输出: ['x', '+', 'y', '+', 'z']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 18:31:45