pop() 不是函数 - nodejs

Cel*_*aro 5 javascript node.js

当我pop()在数组上调用函数时,NodeJS 出现一个奇怪的错误,它说TypeError: cars.pop is not a function......我很困惑。

有什么帮助吗?下面是代码。谢谢,

//callback chaining to avoid having multiple callbacks in the event queue
//only one callback calling others
function showCar(car, callback) {
  console.log('Saw a ' + car);
  if (car.length) {
    //register the function as asynchronous
    process.nextTick(function() {
      callback();
    })
  }
}

function logCars(cars) {
  var car = cars.pop();
  showCar(car, function() { //chaining of call backs
    logCars(car);
  });
}
var cars = ['ferrari', 'porsh', 'Hyundai', 'Peugeot'];
logCars(cars);
Run Code Online (Sandbox Code Playgroud)

Jos*_*ier 4

logCars这是因为您在第二次调用时没有将数组传递给函数。您将在第二次递归调用中传递弹出的字符串。

换句话说,logCars(car)应该是logCars(cars)嵌套回调的地方:

function logCars (cars){
  var car = cars.pop();
  showCar(car, function () {
    logCars(cars); // This should be `cars`, not `car` like you had
  });
}
Run Code Online (Sandbox Code Playgroud)