4 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個贊
起初,Chase的答案似乎是正確的(使用遞歸),但似乎您希望您的代碼僅遵循提供給函數(shù)的路徑。
如果您確定要更改的元素的位置,您仍然可以使用遞歸方法:
純 JS 遞歸解決方案
var myArray = [
[
[],
[]
],
[
[],
[],
[],
[]
],
[
[],
[
[
['needle']
]
]
]
];
function changeNeedle(arr, content, position) {
// removes first element of position and assign to curPos
let curPos = position.shift();
// optional: throw error if position has nothing
// it will throw an undefined error anyway, so it might be a good idea
if (!arr[curPos])
throw new Error("Nothing in specified position");
if (!position.length) {
// finished iterating through positions, so populate it
arr[curPos] = content;
} else {
// passes the new level array and remaining position steps
changeNeedle(arr[curPos], content, position);
}
}
// alters the specified position
changeNeedle(myArray, 'I just got changed', [2, 1, 0, 0]);
console.log(myArray);
但是,如果要搜索與內(nèi)容對應(yīng)的元素,仍必須循環(huán)訪問每個元素。

TA貢獻(xiàn)2039條經(jīng)驗(yàn) 獲得超8個贊
如果要避免導(dǎo)入庫,則具有就地更新的特定于陣列的解決方案將如下所示:
function changeNeedle(searchValue, replaceWith, inputArray=myArray) {
inputArray.forEach((v, idx) => {
if (v === searchValue) {
inputArray[idx] = replaceWith;
} else if (Array.isArray(v)) {
changeNeedle(searchValue, replaceWith, v);
}
});
return inputArray;
}
然后,您可以調(diào)用,并且您的值將被更改以將 的實(shí)例更改為 。changeNeedle('needle', 'pickle', myArray);myArrayneedlepickle
返回值,然后如下所示:myArray
JSON.stringify(myArray, null, 4);
[
[
[],
[]
],
[
[],
[],
[],
[]
],
[
[],
[
[
[
"pickle"
]
]
]
]
]
更新:根據(jù)您的回復(fù),遵循已知更新的確切路徑的非遞歸解決方案。
function changeNeedle(newValue, atPositions = [0], mutateArray = myArray) {
let target = mutateArray;
atPositions.forEach((targetPos, idx) => {
if (idx >= atPositions.length - 1) {
target[targetPos] = newValue;
} else {
target = target[targetPos];
}
});
return mutateArray;
}
請參見:https://jsfiddle.net/y0365dng/

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個贊
不,你不能。
執(zhí)行此操作的最簡單方法是存儲要修改的數(shù)組 () 和鍵 ()。然后,您只需要進(jìn)行常規(guī)分配,例如.array = myArray[2][1][0]index = 0array[index] = value
您可以考慮以下實(shí)現(xiàn):
function changeNeedle(value, keys) {
let target = array;
for (const i of keys.slice(0, -1)) {
target = target[i];
}
target[keys[keys.length - 1]] = value;
}
添加回答
舉報(bào)