设计思路
- 输入验证:首先对输入的路径数组(用于定位嵌套数组中的元素位置)进行验证,确保每个索引都是有效的数字且不越界。
- 遍历数据结构:使用循环或递归的方式,沿着路径数组逐步深入到嵌套数组中,找到目标元素。
- 安全处理:在遍历过程中,检查当前位置的数据类型是否为数组,如果不是则抛出错误。同时处理索引越界的情况。
- 修改操作:找到目标元素后,进行修改操作,并返回修改后的整个数据结构。
实现代码
function safeAccessAndModify(complexData, path, value) {
// 验证路径是否有效
if (!Array.isArray(path) || path.some(index => typeof index!== 'number' || index < 0)) {
throw new Error('Invalid path');
}
let current = complexData;
for (let i = 0; i < path.length - 1; i++) {
const index = path[i];
if (!Array.isArray(current) || index >= current.length) {
throw new Error('Index out of bounds or data type mismatch');
}
current = current[index];
}
const lastIndex = path[path.length - 1];
if (!Array.isArray(current) || lastIndex >= current.length) {
throw new Error('Index out of bounds or data type mismatch');
}
current[lastIndex] = value;
return complexData;
}
使用示例
let complexData = [[1, 2, [3, 4]], [5, [6, 7]], 8];
// 将 [1, 2, [3, 4]] 中的 4 修改为 40
let newComplexData = safeAccessAndModify(complexData, [0, 2, 1], 40);
console.log(newComplexData);