/    Sign up×
Community /Pin to ProfileBookmark

Array to arguments function possible?

I see how the arguments of a function can be passed, displayed in and operated on in the following “findMax” function.

[code=php]
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″ />

<title> HTML5 page </title>

</head>
<body>

<script type=”text/javascript”>
// Following from: http://www.w3schools.com/js/js_function_parameters.asp

function findMax() {
// alert(‘findMax: ‘+[].join.call(arguments, ‘ : ‘)); // this demo shows arguments as an array
var i, max = 0;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) { max = arguments[i]; } // shows arguments can be accessed
}
return max;
}
x = findMax(1, 123, 500, 115, 44, 88);
alert(‘maximum: ‘+x);

// Trying to go the other way: Array to arguments pseudo-array
tarr = [1,2,3,4,5,6,7,8,9];
function createArguments(tarr) {
// alert(‘create: ‘+[].join.call(arguments, ‘ : ‘)); // this demo shows arguments as an array
// for (var i=0; len=tarr.length, i<len; i++) { arguments.push(tarr[i]); } // cannot push an argument list
return tarr.toString(); // creates a string same as .join() which is NOT an arguments display
}
var args = createArguments(tarr);
alert(‘arguments: ‘+args);
alert(‘maximum (version 2): ‘+findMax(args)); // returns 0 because there are no args for findMax function

</script>

</body>
</html>
[/code]

What I have NOT been able to accomplish, as tried above, is to go the other way:
Make an arguments (list, object, term?) from an array.

It this possible? Can an array be transferred into a arguments list and used in a different function?
?

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@mrhooMay 09.2015 — Array's apply method uses the array passed as a second parameter as the arguments object of the function being applied to.

[CODE]function findMax(){
var i, max= 0;
for(i= 0; i<arguments.length; i++){
if(arguments[i]>max){
max= arguments[i];
}
}
return max;
}[/CODE]

[B]var x= [1, 123, 500, 115, 44, 88];

alert('maximum: '+findMax.apply(Array,x));[/B]
Copy linkTweet thisAlerts:
@JMRKERauthorMay 09.2015 — Thanks for the answer, but that is not what I'm trying to find out about.

The 'findMax' function works OK as is and as far as I can see your version does the same thing.

What I trying to figure out is how to create the arguments list from an array.


For a non-working example:

max = findMax(1,2,3,4,5); // would return maximum value (5) of a list variable number of parameters.

I want to know if the list of parameters could be created like this

args = new Array(1,2,3,4,5); // allow any number of parameters

max = findMax(args); // where args would be the native values of 'arguments' within the function.


My guess at this time is that it can not be done.


Or that the function should be re-written to accept arrays (as you have done in your example provided) and NOT arguments

But if that is so, then why have the 'arguments' variable within any function of the JS language?

Maybe I'm just not asking the question the correct way?

But thanks for you alternate function demonstrating another way to "skin the cat" in JS.
Copy linkTweet thisAlerts:
@TcobbMay 09.2015 — It can be done if you don't mind committing what is (to some people) the unpardonable sin of using 'eval'

[CODE]function speak(){ //just prints all args sent to it
var i, z = arguments.length;
for(i = 0; i < z; i++){
console.log(arguments[i]);
}

}


function many(fnc, arr){ //first arg is the function, second is the array to be converted into args
var str, i, len, com;
len = arr.length;
str = '';
for(i = 0; i < len; i++){
if(typeof(arr[i]) === 'string'){ //to insure that string data is interpreted as string
arr[i] = '"' + arr[i] + '"';
}
}
str = arr.join(',');
com = 'fnc(' + str + ')';
eval(com);
}

many(speak,['alpha','beta','gamma', 44, 12]);
[/CODE]
Copy linkTweet thisAlerts:
@JMRKERauthorMay 10.2015 — Thanks "Tcobb". I'm not sure how useful the technique or function would be since .apply() and .call() are available in most browsers.

I was just interested in knowing

if the arguments could be converted [B]to[/B] an array [B]from[/B] the function arguments

what the [B]reverse action[/B] (to arguments from and array) would look like or if was possible to be done.
Copy linkTweet thisAlerts:
@ryanpillerinMay 10.2015 — You mean like this?
[CODE]
<!DOCTYPE html>
<html>
<body>

<p>Finding the largest number.</p>
<p id="demo"></p>

<script>
function findMax() {
var i, max = 0;
console.log(arguments);
for(i = 0; i < arguments[0].date.length; i++) {
if (arguments[0].date[i] > max) {
max = arguments[0].date[i];
}
}
return max;
}
document.getElementById("demo").innerHTML = findMax({date: [1,2,3,4]});
</script>

</body>
</html>
[/CODE]
Copy linkTweet thisAlerts:
@JMRKERauthorMay 10.2015 — Yes, that makes sense now, but I never would have come up with it myself.

I modified your code a bit because the 'date' parameter threw me off for a bit.

I also show that both literal array can be used with literal parameters

as well as with a variable array assignment.

Neat. Thank you 'ryanpillerin'

[code=php]
<!DOCTYPE html>
<html>
<body>

<p>Finding the largest number.</p>
<p id="demo"></p>

<script>
function findMax() {
var i, max = 0; // console.log(arguments);
for(i = 0; i < arguments[0].argArr.length; i++) {
if (arguments[0].argArr[i] > max) { max = arguments[0].argArr[i]; }
}
return max;
}
document.getElementById("demo").innerHTML = findMax({argArr: [1,2,3,4]}); // literal array



var tarr = [1,5,100,5,1];
document.getElementById("demo").innerHTML += '<p>Maximum: ' + findMax({argArr: tarr});

function avg() {
var i, sum = 0, cnt = arguments[0].argArr.length; // console.log(arguments);
for(i = 0; i < cnt; i++) { sum += arguments[0].argArr[i]; }
return sum / cnt;

}
document.getElementById("demo").innerHTML += '<p>Average: ' + avg({argArr: tarr});

</script>

</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@Jeff_MottMay 10.2015 — args = new Array(1,2,3,4,5);
max = findMax.apply(null, args);


This use of apply() is also what mrhoo was trying to demonstrate above.
Copy linkTweet thisAlerts:
@JMRKERauthorMay 10.2015 — args = new Array(1,2,3,4,5);
max = findMax.apply(null, args);


This use of apply() is also what mrhoo was trying to demonstrate above.[/QUOTE]


You're right.

I was just too confused to see the equivalency.

The function I was looking for to do the reverse actions looks like the .apply()

while the .call() is used for the literal assignment or calling the function directly with literal parameters.

[code=php]
<!DOCTYPE html>
<html>
<body>

<p>Finding the largest number.</p>
<p id="demo"></p>

<script>
function findMax(){
var i, max= 0;
for(i= 0; i<arguments.length; i++) {
if (arguments[i]>max) { max = arguments[i]; }
}
return max;
}
document.getElementById("demo").innerHTML = 'arguments: 1,2,3,4<br>max: '+findMax(1,2,3,4); // literal arguments
document.getElementById("demo").innerHTML += '<p>arguments: 1,2,3,4<br>max: '+findMax.call(null,1,2,3,4); // literal arguments

var x = [1, 123, 500, 115, 44, 88];
document.getElementById('demo').innerHTML += '<p>array: '+x+'<br>maximum: '+findMax.apply(Array,x);



var tarr = [1,5,100,5,1];
function avg() {
var i, sum = 0, cnt = arguments.length; // console.log(arguments);
for(i = 0; i < cnt; i++) { sum += arguments[i]; }
return sum / cnt;
}
document.getElementById("demo").innerHTML += '<p>array: '+tarr+'<br>Average: ' + avg.apply(Array,tarr);


</script>

</body>
</html>

[/code]
×

Success!

Help @JMRKER spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...