简体   繁体   English

Javascript-带对象的回调

[英]Javascript - callback with objects

I have a problem with callback function. 我对回调函数有问题。 I want write a function, who can iterate the object (i want use a callback method), but it's not working and i don't know what is wrong with this. 我想编写一个可以迭代对象的函数(我想使用回调方法),但是它不起作用,我不知道这有什么问题。

I'll be glad from any help. 任何帮助我都会很高兴。

   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 */

The problem is the 问题是

 getAll (0, services.length, getAll)

services.length return the length of an array, but arrays start at position 0 services.length返回数组的长度,但是数组从位置0开始

to fix this error use 解决此错误使用

 getAll (0, services.length-1, getAll)

The error you get is due to calling services[2] that doesn't exists. 您收到的错误是由于调用不存在的services [2]引起的。 This getAll function below solves your problem 下面的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM