2

Is there any equivalent function in JavaScript (NodeJS) similar to PHP's call_user_func_array (http://php.net/manual/en/function.call-user-func-array.php). Which allows to call a function with array of parameters.

In my case, I have to call util.format with parameters that will be in an array.

Here is very simple example trying to show it.

var util = require("util");

function my_fundtion(items) {
  var format_string = "";
  for (var i=0; i < items.length; i++) {
    format_string += " %s";
  }
  return util.format(format_string, /* here I want to pass items in items array */);
}
5
  • In your example, do you mean: for (var i=0; i < items.length; i++) { format += " " + items[i]; } Are you also doing a string replace on format_string from your util.format? Commented Nov 13, 2014 at 15:10
  • Javascript has : myFunction.apply(object or null, args) Commented Nov 13, 2014 at 15:12
  • @thiswayup No, it is to get same number of placeholders as array items. Commented Nov 13, 2014 at 15:15
  • BTW, format_string will always be empty Commented Nov 13, 2014 at 15:18
  • @LuisMasuelli corrected that. Commented Nov 14, 2014 at 6:55

2 Answers 2

3

PHP has:

call_user_func_array('myfunc', array(1, 2, "foo", false));

While JS has:

myfunc.apply(null, [1, 2, "foo", false]);

The first null goes in the position of an object. You will make use of that if the function is intended to be a method. An example on using such invocation would be to slice array-like objects which are not arrays at all but seem like one (like the arguments object inside of a function):

Array.prototype.slice.apply(arguments, []);

Generally speaking, the syntax is:

(afunction).apply(obj|null, array of arguments)

You can try this:

function my_fundtion(items) {
    var format_string = "";
    for (var i=0; i < items.length; i++) {
        format_string += " %s";
    }
    var new_items = items.slice();
    new_items.unshift(format_string);
    return util.format.apply(null, new_items);
}

IMHO that's the wrong approach for a function. Have you tried the following?

function my_fundtion(items) {
    return items.join(" ");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! myfunction.apply() helped. Yeah, array.join() to be used, forgot about that :)
0

Because call_user_func_array call function referenced by the function name which is in string. So, in JS we need to use eval.

Example:

const popup = (msg) => {
 alert(msg);
}

const subject = {
 popup(msg) {
  alert(msg);
 }
}

So,

eval("popup").apply(null, ['hi'])
eval("subject.popup").apply(null, ['hi'])

Correct me. If i wrong. ;)

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.