[英]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.