简体   繁体   中英

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

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. This getAll function below solves your problem

   function getAll(index, count, callback) {
       if (index < count) {
           service = new Service(services[index]);
           console.log(service)
           callback(index + 1, count, getAll)
       }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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