在JavaScript中,可以使用递归函数来遍历数组并动态查找深层嵌套的值。以下是一个示例代码:
function findNestedValue(arr, searchKey) {
let result;
arr.forEach(function(item) {
if (typeof item === 'object' && item !== null) {
// 如果当前项是对象,则递归调用findNestedValue函数
result = findNestedValue(Object.values(item), searchKey);
} else if (Array.isArray(item)) {
// 如果当前项是数组,则递归调用findNestedValue函数
result = findNestedValue(item, searchKey);
} else if (item === searchKey) {
// 如果当前项等于搜索键,则返回结果
result = item;
}
// 如果已经找到结果,则跳出forEach循环
if (result) {
return;
}
});
return result;
}
// 示例数组
const arr = [
1,
[2, 3],
{
key: 'value',
nestedArray: [4, 5, { nestedKey: 'nestedValue' }]
}
];
// 查找嵌套值
const searchKey = 'nestedKey';
const result = findNestedValue(arr, searchKey);
console.log(result); // 输出 "nestedValue"
在上面的示例代码中,我们定义了一个名为findNestedValue
的递归函数。它接受两个参数:待查找的数组arr
和搜索键searchKey
。函数会遍历数组中的每一项,并根据当前项的类型进行不同的处理:
findNestedValue
函数。findNestedValue
函数。result
变量,并跳出循环。forEach
循环。最后,我们将示例数组arr
和搜索键searchKey
传递给findNestedValue
函数,并打印结果。在这个示例中,函数将返回字符串"nestedValue",这是位于arr
数组中嵌套对象的nestedKey
的值。