Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: passing multiple arguments as a single variable

is it possible to pass multiple arguments using a single variable? For example, if I wanted to do something like:

function foo(x,y){
    document.write("X is " + x);
    document.write("Y is " + y);
}

var bar = "0,10";
foo(bar);

The example above is an simplified example of what I was trying to do. It doesn't work (because the "bar" is detected as a single argument). I know that there are easier ways to implement this using arrays.

So, I ask this question mostly out of curiosity - is it possible to get the "bar" variable to be detected as not one, but 2 arguments?

Thanks!

like image 728
user418797 Avatar asked Aug 12 '10 19:08

user418797


People also ask

How do I pass multiple values to a variable in JavaScript?

JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array or the object. Use destructuring assignment syntax to unpack values from the array, or properties from objects.

Can a variable hold multiple values in JavaScript?

There is no way to assign multiple distinct values to a single variable. An alternative is to have variable be an Array , and you can check to see if enteredval is in the array. To modify arrays after you have instantiated them, take a look at push , pop , shift , and unshift for adding/removing values.

How do you pass multiple parameters to a function?

The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.

Which function accepts two arguments in JavaScript?

Let's start by creating a function called add that can accept 2 arguments and that returns their sum. We can use Node. js to run the code node add_2_numbers.


1 Answers

function foo(thing) {
    document.write("X is " + thing.x);
    document.write("Y is " + thing.y);
}

var bar = {x:0, y:10};
foo(bar);
like image 169
jtbandes Avatar answered Sep 21 '22 14:09

jtbandes