当我在数组上调用函数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);
最佳答案
这是因为您没有在第二个调用中将数组传递给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
});
}