当我在一个数组上调用函数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);
答案 0 :(得分:3)
这是因为你没有在第二次调用时将数组传递给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
});
}