我的回调函数有问题。我想写一个函数,谁 可以迭代对象(我想使用回调方法),但事实并非如此 工作,我不知道这有什么问题。
在任何帮助下我都会很高兴。
services = [
{
name: "a",
},
{
name: "b"
}
]
function Service (data) {
this.name = data.name
}
function getData (i) {
sample = new Service(services[i])
console.log(sample)
}
getData(0) /* this function work*/
function getAll(index, count, callback) {
service = new Service(services[index]);
console.log(service)
if (index < count) {
callback(index + 1, count, getAll)
}
}
getAll (0, services.length, getAll) /* this function is not working */
答案 0 :(得分:0)
问题是
getAll (0, services.length, getAll)
services.length返回数组的长度,但数组从位置0开始
修复此错误使用
getAll (0, services.length-1, getAll)
答案 1 :(得分:0)
您得到的错误是由于调用不存在的服务[2]。 下面的getAll函数解决了您的问题
function getAll(index, count, callback) {
if (index < count) {
service = new Service(services[index]);
console.log(service)
callback(index + 1, count, getAll)
}
}