[英]Javascript - callback with objects
我对回调函数有问题。 我想编写一个可以迭代对象的函数(我想使用回调方法),但是它不起作用,我不知道这有什么问题。
任何帮助我都会很高兴。
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 */
问题是
getAll (0, services.length, getAll)
services.length返回数组的长度,但是数组从位置0开始
解决此错误使用
getAll (0, services.length-1, getAll)
您收到的错误是由于调用不存在的services [2]引起的。 下面的getAll函数解决了您的问题
function getAll(index, count, callback) {
if (index < count) {
service = new Service(services[index]);
console.log(service)
callback(index + 1, count, getAll)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.