简单的javascript递归函数返回的值比实际存在的值多

Simple javascript recursive function returns more values than actually exist?

本文关键字:存在 递归函数 返回 简单 javascript      更新时间:2023-09-26

我正在练习递归,并编写了这个函数:

var bigArray = ['a', ['b', ['c', ['d', {a:'e'}]]]];
var results = [];
function bagger293(bigArray){
  for (var item in bigArray){
    if (Array.isArray(bigArray[item])){
      bagger293(bigArray[item]);
    }
     else if (typeof bigArray[item] === 'object'){
      bagger293(bigArray[item]);
    }else{
      results.push(bigArray[item]);
    }
  }
}
bagger293(bigArray);
console.log(results);

我只是希望函数将任何单个值压入数组,如果它是对象或数组,则进行更深入的搜索。奇怪的是,我的函数返回这个:

[ 'a', 'b', 'c', 'd', 'e', 'd', 'e', 'c', 'd', 'e', 'd', 'e', 'b', 'c', 'd', 'e', 'd', 'e', 'c', 'd', 'e', 'd', 'e' ]

我认为这是因为我指定

的方式

bigArray[item],但不知道为什么。

预期结果:

['a', 'b', 'c', 'd', 'e']

您缺少一个else。一旦你发现了一个数组,就不要再用它做其他事情了。

var bigArray = ['a', ['b', ['c', ['d', { a: 'e' }]]]];
var results = [];
function bagger293(bigArray) {
  for (var item in bigArray) {
    if (Array.isArray(bigArray[item])) {
      bagger293(bigArray[item]);
    } 
    else if (typeof bigArray[item] === 'object') {   // <--
      bagger293(bigArray[item]);
    } 
    else {
      results.push(bigArray[item]);
    }
  }
}
bagger293(bigArray);
console.log(results);

另一方面,由于所有数组都是对象,您可以只测试'object':

var bigArray = ['a', ['b', ['c', ['d', { a: 'e' }]]]];
var results = [];
function bagger293(bigArray) {
  for (var item in bigArray) {
    if (typeof bigArray[item] === 'object') {
      bagger293(bigArray[item]);
    } 
    else {
      results.push(bigArray[item]);
    }
  }
}
bagger293(bigArray);
console.log(results);

您缺少一个else。因为数组也是一个对象,所以代码会启动两次递归。

正在运行:

function bagger293(bigArray){
  for (var item in bigArray){
    if (Array.isArray(bigArray[item])){
      bagger293(bigArray[item]);
    }else if (typeof bigArray[item] === 'object'){
      bagger293(bigArray[item]);
    }else{
      results.push(bigArray[item]);
    }
  }
}

所有数组都是对象。不需要同时检查Array.isArraytypeof == 'object'

var bigArray = ['a', ['b', ['c', ['d', {a:'e'}]]]];
var results = [];
(function bagger293(bigArray) {
  for (var item in bigArray)
    if (typeof bigArray[item] === 'object')
      bagger293(bigArray[item]);
    else
      results.push(bigArray[item]);
})(bigArray);
console.log(results);