user3450590
user3450590

Reputation: 341

apply method not returning full array value in javascript

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

Answers (2)

Felix Kling
Felix Kling

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:

  • Wrap the argument passed to .apply in another array: getanimalsinfo.apply(obj, [arr])
  • Use a rest parameter in your function definition: function(...a) { /*...*/ }

Have a look at the MDN documentation for more info:

Related:

Upvotes: 6

Mamun
Mamun

Reputation: 68933

You can use arguments:

var obj={name: 'Dogs'};
var arr=['india','slovenia','scotland'];

var getanimalsinfo = function(){
    return this.name + ' is good animal found in '+ arguments[2]

}
console.log(getanimalsinfo.apply(obj, arr));

Upvotes: 1

Related Questions