How to return an array in javascript?

Asked

Viewed 2,549 times

1

I have a function to upload images and for now the imgs array is going to global scope, but I wish this function could return this array:

function loadImages () {
    imgs = [];
    for (var i in arguments) {
        var start = arguments[i].lastIndexOf("/") + 1;
        var end = arguments[i].indexOf(".");
        var name = arguments[i].substring(start, end);
        imgs[name] = new Image();
        imgs[name].src = arguments[i];
    }
}
  • 2

    after for add: Return imgs;

  • 1

    I managed to settle by changing at first to var imgs = new Object() and in the end the Return imgs

1 answer

1

I would like to add a few points:

function loadImages () {
    let imgs = []; // se usar let não vai alterar nenhum imgs[] fora desse escopo

    // forEach percorre um array com o intuito de gerar side-effects
    // se arguments for um array-like, tem que converter com o  Array.from()
    // mas vou assumir que não é:
    arguments.forEach(x => {
        // regex que seleciona o que estiver entre o ultimo / e . 
        var name = x.match(/(.*)\/(.*)\./).pop(); 
        imgs[name] = new Image();
        imgs[name].src = x;
    });

    return imgs; //retorna o imgs como perguntado
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.