# JS怎樣替換數組中的特定值
在JavaScript中,替換數組中的特定值是常見的操作。以下是幾種常用的方法:
## 1. 使用`findIndex`和索引賦值
```javascript
const arr = [1, 2, 3, 4];
const index = arr.findIndex(item => item === 3);
if (index !== -1) {
arr[index] = 99; // 替換3為99
}
map
創建新數組const newArr = arr.map(item => item === 3 ? 99 : item);
splice
方法const index = arr.indexOf(3);
if (index > -1) {
arr.splice(index, 1, 99); // 刪除1個元素并插入新值
}
forEach
直接修改arr.forEach((item, i) => {
if (item === 3) arr[i] = 99;
});
findIndex
+深度比較map
可能不如循環高效根據場景選擇合適的方法,需要不可變數據時選擇map
,否則直接修改原數組更高效。
“`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。