Some functions allow multiple parameters, but we can't pass them directly. ES5 has apply() method to that. ES6 provides spread operator. Lets see them here
apply() method syntax
fun.apply(thisArg, [argsArray])
thisArg - context of the function. if code in non strict mode, null and undefined will be replaced by global object.
argsArray - its an array
Using ES5 apply method
Observe below code. Here we are finding maximum number in array of numbers. We don't need any context here to apply, so we can pass null or undefined
Math.max.apply(null, [1, -5, 10, 8])Click here to see DEMO
var arr1 = ['a', 'b']; var arr2 = ['c', 'd']; arr1.push.apply(arr1, arr2); // arr1 is now ['a', 'b', 'c', 'd']Click here to see DEMO
Using ES6
Use spread operator to pass array as parameter values
var maxVal = Math.max(...[-1, 5, 11, 3]); console.log(maxVal);Click here to see DEMO
const arr1 = ['a', 'b']; const arr2 = ['c', 'd']; arr1.push(...arr2); console.log(arr1);Click here to see DEMO
0 comments:
Post a Comment