我有一个 n 维数组,我想使用另一个数组来指定索引来访问/修改其中的元素。
我知道如何访问一个值,但我不知道如何修改原始值。
// Arbitrary values and shape
arr = [[[8, 5, 8],
[9, 9, 9],
[0, 0, 1]],
[[7, 8, 2],
[9, 8, 3],
[9, 5, 6]]];
// Arbitrary values and length
index = [1, 2, 0];
// The following finds the value of arr[1][2][0]
// Where [1][2][0] is specified by the array "index"
tmp=arr.concat();
for(i = 0; i < index.length - 1; i++){
tmp = tmp[index[i]];
}
// The correct result of 9 is returned
result = tmp[index[index.length - 1]];
如何修改数组中的值?
是否有更好/更有效的方法来访问值?
最佳答案
这是一个经典的递归算法,因为每个步骤都包含相同的算法:
- 从索引中弹出第一个索引。
- 继续处理新弹出的索引指向的数组。
直到到达索引
中的最后一个元素 - 然后替换最低级别数组中的相关元素。
function getUpdatedArray(inputArray, indices, valueToReplace) {
const ans = [...inputArray];
const nextIndices = [...indices];
const currIndex = nextIndices.shift();
let newValue = valueToReplace;
if (nextIndices.length > 0) {
newValue = getUpdatedArray(
inputArray[currIndex],
nextIndices,
valueToReplace,
);
} else if (Array.isArray(inputArray[currIndex])) {
throw new Error('Indices array points an array');
}
ans.splice(currIndex, 1, newValue);
return ans;
}
const arr = [
[
[8, 5, 8],
[9, 9, 9],
[0, 0, 1]
],
[
[7, 8, 2],
[9, 8, 3],
[9, 5, 6]
]
];
const indices = [1, 2, 0];
const newArr = getUpdatedArray(arr, indices, 100)
console.log(newArr);
关于javascript - 如何修改n维数组元素的值,其中索引由Javascript中的数组指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61263774/