T. Close T. Close - 6 months ago 10
Javascript Question

JavaScript - losing array index after using "apply"



// this is not looping through the "girls" array as expected, but breaking down
// the first element of the array to its char elements

var girls = ["sandy","katie","lynda","wendy"];

function showGirlsTalent(girl) {

for (var i in girl) {

var rand = Math.floor(Math.random() * this.talents.length + 1);
console.log(girl[i] + ' can ' + this.talents[rand]);
}
}

var talent = {

talents:['dance','sing','act']
}

function createTalent(girl, callback) {

showGirlsTalent.apply(callback,girl);
}

createTalent(girls, talent);




Answer

In your fun.apply(thisArg, argsArray) invocation, argsArray = ["sandy","katie","lynda","wendy"], so you end up calling showGirlsTalent("sandy","katie","lynda","wendy"). You only use the first argument in showGirlsTalent and loop through it via for..in getting the individual characters.

You can figure this easily by using a debugger in your favorite browser. Do you know how to use it?

Comments