如何使用数组A作为导航路径遍历数组B(禁用eval)
解决方案:通过导航路径数组安全遍历嵌套结构
这问题我平时写业务代码时经常碰到,用Array.prototype.reduce就能完美解决,完全不需要碰eval——毕竟eval不仅有安全风险,后续维护起来也容易踩坑。
核心思路
利用reduce的累积特性,从目标结构(数组B)开始,沿着路径数组A的每一项逐步深入访问,每一步的结果作为下一次访问的起点,最终得到目标值。这个方法同时兼容数组索引(数字)和对象属性(字符串),通用性拉满。
基础实现代码
// 你的导航路径数组 const path = [1, "testSuites", 20, "testCases", 1]; // 你的目标嵌套数组/对象 const targetArray = [/* 这里是你的数组B内容 */]; function getNestedValue(target, path) { return path.reduce((currentLevel, key) => { // 边界防护:如果当前层级不存在,直接返回undefined避免报错 if (currentLevel === undefined || currentLevel === null) { return undefined; } // 访问当前层级的对应键/索引 return currentLevel[key]; }, target); // 初始值设为目标结构(数组B) } // 调用示例 const result = getNestedValue(targetArray, path); console.log(result); // 等效于 targetArray[1]["testSuites"][20]["testCases"][1]
带默认值的增强版
如果需要在路径不存在时返回指定默认值,可以修改函数如下:
function getNestedValue(target, path, defaultValue) { const finalValue = path.reduce((currentLevel, key) => { if (currentLevel === undefined || currentLevel === null) { return undefined; } return currentLevel[key]; }, target); // 如果最终值未找到,返回默认值 return finalValue !== undefined ? finalValue : defaultValue; } // 使用示例 const result = getNestedValue(targetArray, path, "未找到对应值");
为什么不用eval?
eval会执行传入的字符串代码,不仅容易被注入恶意代码,而且如果路径数组内容动态变化,拼接字符串的过程很容易出错,调试起来也麻烦。用reduce的方式更安全、更清晰,也符合函数式编程的最佳实践。
内容的提问来源于stack exchange,提问作者Lolpez
相关产品推荐
相关产品推荐

