To show the elements from the array with call () method

To show the elements from the array with call () method
0

#1

Hi, I have a problem with fn.call () within a method in an object. I have an arrangement that internally has objects, the values of these objects are type and gender.

when making the sentence of victor.listarGustos (tastes) is only returning me ‘books: futurists’ that is to say only the first value of the array is returning me, and what I am looking for is that I get the whole array, type:’ books’, genre: ‘futurists’
type: ‘music’, genre: ‘rap’
Any correction that I must make to my code?

    const gustos = [
    {tipo:'libros', genero: 'futuristas'},
    {tipo:'musica', genero: 'rap'}
]

class User{
    constructor(name){
        this.name = name
    }
    listarGustos(arr){
        length = arr.length
        console.log(arr)
        for(let i = 0; i <length; i++){    
        return function (i){
             console.log(`${this.tipo} : ${this.genero}`)
             console.log(i)
         }.call(arr[i])
        }
    }
}
const victor = new User("victor")

victor.listarGustos(gustos)

#2

I must be missing something. If you just want to return the array passed into listarGustos, why not just write the following and skip the whole returning a function part.

 return arr;

Maybe you meant to say you want the console.log statements to execute for each object inside the array? If that is what you want, then you need to understand that as soon as you write return that the for loop and current function is immediately exited. You could use a IIFE (Immediately Invoked Function Expression) and wrap your return function part as follows which might accomplish what you are trying to do:

	listarGustos(arr) {
		length = arr.length;
		for (let i = 0; i < length; i++) {
			(function(i) {
				return function() {
					console.log(`${this.tipo} : ${this.genero}`);
				}.call(arr[i]);
			})(i);
		}
	}

Using the modified version of your original listartGustos function would result in displaying the following in the console:

libros : futuristas
musica : rap


#3

Thank you, more or less that what I was looking for.