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.

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

5 Comments

ok, then how to get this result: 'dog is good animal found in india, slovenia, scotland' using APPLY??
@user3450590 with .call instead of .apply.
@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.
@FelixKling with apply, he should have used function(arg1, arg2, arg3) instead of function(a) ?
@Cid: Really depends on how the function should work.
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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.