admin管理员组

文章数量:1333451

I am having a strange error with NodeJS when I call the function pop() on an array, it says TypeError: cars.pop is not a function... I am confused.

Any help? Below is the code. Thank you,

//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);

I am having a strange error with NodeJS when I call the function pop() on an array, it says TypeError: cars.pop is not a function... I am confused.

Any help? Below is the code. Thank you,

//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);
Share Improve this question edited Jan 30, 2017 at 3:40 Josh Crozier 241k56 gold badges400 silver badges313 bronze badges asked Jan 30, 2017 at 0:28 CelaroCelaro 2262 gold badges8 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

It's because you aren't passing an array to the logCars function on the second call. You are passing the popped string on the second recursive call.

In other words, logCars(car) should be logCars(cars) where you are nesting callbacks:

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

本文标签: javascriptpop() is not a functionnodejsStack Overflow