3

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.

Baljeetsingh Sucharia
  • 1,990
  • 1
  • 19
  • 37
user3450590
  • 341
  • 2
  • 14

2 Answers2

6

.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:

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • ok, then how to get this result: 'dog is good animal found in india, slovenia, scotland' using APPLY?? – user3450590 Dec 06 '18 at 08:12
  • @user3450590 with `.call` instead of `.apply`. – Nika Dec 06 '18 at 08:13
  • 1
    @user3450590: If you defined the function as `function(...args) {...}` and did `' is good animal found in ' + args.join()`. But you shouldn't define the function based on the fact that you want to use `.apply`. You should decide first whether you want the function to be variadic or accept an array as argument. And based on that you choose either `.apply` or `.call`. – Felix Kling Dec 06 '18 at 08:15
  • @FelixKling with apply, he should have used `function(arg1, arg2, arg3)` instead of `function(a)` ? – Cid Dec 06 '18 at 09:20
  • @Cid: Really depends on how the function should work. – Felix Kling Dec 06 '18 at 09:22
1

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));
Mamun
  • 66,969
  • 9
  • 47
  • 59