我有以下圖表:
const array = [
["one", true],
["two", false],
["three", false],
["four", true]
]
我希望在值為 true 時添加此變數:
const add = ["ok"]
所以最終它看??起來像這樣:
[
[ 'one', true, 'ok' ],
[ 'two', false ],
[ 'three', false ],
[ 'four', true, 'ok' ],
]
目前,我正在嘗試 .map 方法:
const testBoolean = array.map(el => {
if (el[1] === true){
array.push(add)
}
})
console.log(array)
但我不知道在哪里告訴它推到第 3 行...
感謝您的幫助,祝您有美好的一天 :) !
uj5u.com熱心網友回復:
如果您的意思是 forEach,請不要使用 map。僅在需要結果陣列時才使用 map - 在這種情況下 testBoolean 將是一個地圖
你要這個
const array = [
["one", true],
["two", false],
["three", false],
["four", true]
]
const add = ["ok"]
array.forEach(el => {
if (el[1] === true) { // or just if (el[1]) if you are sure it is always a boolean
el.push(...add) // or add[0]
}
})
console.log(array)
uj5u.com熱心網友回復:
只需回圈使用陣列forEach并檢查第一個索引是否為真。對于布林值,您不需要將其與真或假進行比較。
const array = [
["one", true],
["two", false],
["three", false],
["four", true]
];
const add = ["ok"]
array.forEach(item => {
if(item[1]){
item.push(...add);
}
});
console.log(array)
forEach的檔案
uj5u.com熱心網友回復:
其他方式:
const array = [
["one", true],
["two", false],
["three", false],
["four", true]
];
const add = ["ok"];
for (const item of array) {
item[1] && item.push(add[0]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/465126.html
標籤:javascript 数组 字典 前锋 推
上一篇:在串列字典中查找回圈
下一篇:如何改變字典的位置?[復制]
