I quite understand the basic principle of using .apply() method on JS.
function sayHi(x, y, z) {
console.log("I'm " + this.name + ", My choices are" + x + "," + y + "," + z);
}
var personA = {
name : "Albert"
};
var personB = {
name : "Bob"
};
var name = "Cindy";
var options = [" a", " b", " c"];
sayHi.apply(personA, options); // "I'm Albert, My choices are a, b, c"
sayHi.apply(personB, [" d", " e", " f"]); // "I'm Bob, My choices are d, e, f"
Above snippet is an ideal case where you just want to use certain amount of array's element in sayHi()
function and you pass on the exact same amount of data (array) needed for sayHi()
function.
However, sometimes you need to utilize all of the array's element in given data set where the data could also be in varying amount. So instead of just accepting array with 3 elements, the sayHi()
function can accept and array with 4,5, 6, or more elements, and not just accepting it but also utilizing all of the elements passed, something like this:
function sayHi(....) {
// Accept any array with varying amount of elements, and using it
for (...) {
// A loop that will go through each element in given array
}
}
var personA = {
name : "Albert"
};
var personB = {
name : "Bob"
};
var name = "Cindy";
var options3 = [" a", " b", " c"];
var options4 = [" a", " b", " c", " d"];
var options5 = [" a", " b", " c", " d", " e"];
// and so on
sayHi.apply(personA, options3);
sayHi.apply(personA, options4);
sayHi.apply(personA, options5);
and so far I haven't been able to find a way to do this, so I need your help to explain it to me.
Thanks,