4 回答
TA贡献1810条经验 获得超4个赞
起初,Chase的答案似乎是正确的(使用递归),但似乎您希望您的代码仅遵循提供给函数的路径。
如果您确定要更改的元素的位置,您仍然可以使用递归方法:
纯 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);
但是,如果要搜索与内容对应的元素,仍必须循环访问每个元素。
TA贡献2039条经验 获得超8个赞
如果要避免导入库,则具有就地更新的特定于阵列的解决方案将如下所示:
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;
}
然后,您可以调用,并且您的值将被更改以将 的实例更改为 。changeNeedle('needle', 'pickle', myArray);myArrayneedlepickle
返回值,然后如下所示:myArray
JSON.stringify(myArray, null, 4);
[
[
[],
[]
],
[
[],
[],
[],
[]
],
[
[],
[
[
[
"pickle"
]
]
]
]
]
更新:根据您的回复,遵循已知更新的确切路径的非递归解决方案。
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贡献1820条经验 获得超9个赞
不,你不能。
执行此操作的最简单方法是存储要修改的数组 () 和键 ()。然后,您只需要进行常规分配,例如.array = myArray[2][1][0]index = 0array[index] = value
您可以考虑以下实现:
function changeNeedle(value, keys) {
let target = array;
for (const i of keys.slice(0, -1)) {
target = target[i];
}
target[keys[keys.length - 1]] = value;
}
添加回答
举报
