Reputation: 341
I made an array to be passed in apply method, I was expecting to return full value of array, but when I used index value of array to give value of that index, array method actually returned index of character:
var obj = {
name: 'Dogs'
}
var arr = ['India', 'Slovenia', 'Scotland'];
var getanimalsinfo = function(a) {
return this.name + ' is good animal found in ' + a[2]
}
console.log(getanimalsinfo.apply(obj, arr));
Here, I was expecting "Dog is good animal found in Scotland", but I got : 'Dog is good animal found in d'. Here d is the third index of India. Please let me know what I did wrong. Thanks.
Upvotes: 3
Views: 78
Reputation: 816364
.apply
passes each element of the array as separate argument to the function. I.e. in your case the function is called as getanimalsinfo(arr[0], arr[1], arr[2])
and hence a
will have the value 'india'
.
If you want to pass the array as a single argument (equivalent to getanimalsinfo(arr)
), use .call
instead:
var obj = {
name: 'Dogs'
}
var arr = ['india', 'slovenia', 'scotland'];
var getanimalsinfo = function(a) {
return this.name + ' is good animal found in ' + a[2]
}
console.log(getanimalsinfo.call(obj, arr));
// ^^^^
Alternative solutions:
.apply
in another array: getanimalsinfo.apply(obj, [arr])
function(...a) { /*...*/ }
Have a look at the MDN documentation for more info:
Related:
Upvotes: 6