Arrays Objects Parsing

sono's icon

Hi forum,

I am experiencing difficulties with handling arrays / objects in javascript.

What I am trying to do is to create a randomList() function that can be recalled from other functions, generating random values for any list length. For instance randomList(10, 200, 3000) should output an array of three random values within the ranges of 10, 200 and 3000.

The problem is that when I pass on an array from function X to randomList(), I don't get to parse it properly. This could have something to do with the fact that it's not an actual array, but an object, as it seems the arrayfromargs() function creates an object instead of an array (?).

Herewith a stripped down piece of code that shows my issue:

function list() {
    a = arrayfromargs(messagename, arguments);
    outlet(0, 'typeof a= ' + typeof a);
    outlet(0, 'a= ' +a);
    outlet(0, 'a[0]= '+a[0]);
    outlet(0, 'result= ' + randomList(a));
}

function randomList() {
    b = arrayfromargs(arguments);
    outlet(0, 'typeof b= ' + typeof b);
    outlet(0, 'b= '+b);
    outlet(0, 'b[0]= '+b[0]);
    for (i=0; i<b.length; i++) {
        b[i] = Math.random()*b[i];
    }
    return a;
}

Which prints this in the console after input 10 200 3000 from a message box:

fromJS: typeof a= object
fromJS: a= 10,200,3000
fromJS: a[0]= 10
fromJS: typeof b= object
fromJS: b= 10,200,3000
fromJS: b[0]= 10,200,3000
fromJS: result= 10,200,3000


Here it shows that within list() the array a is parsed correctly as a[0] = 10
However, within randomList(), b[0] equals the full list instead of 10 whilst there should be no difference (?)

----

To put the question another way: How can I modify an array of variable length in a separate function that takes an array as an input, and also returns an array.

Or, how do I parse an object that contains array like content. Also, I don't understand why it's an object anyway instead of an array.

I feel there is some simple solution to this as it should be nothing complicated.

Thanks for your enlightment,
Cheers,
Sono

hollyhook's icon

can you show how you call the function randomList?

sono's icon

Hi,

That's actually already in the code above inside list():

outlet(0, 'result= ' + randomList(a));

sono's icon

Anybody?

ak's icon

just pass args to `randomList` like in a common JS function:


function randomList(b) {
    outlet(0, 'typeof b= ' + typeof b);
    outlet(0, 'b= '+b);
    outlet(0, 'b[0]= '+b[0]);
    for (i=0; i<b.length; i++) {
        b[i] = Math.random()*b[i];
    }
    return b;
}

hth

edit:
Just to clarify, your example doesn't work because you pass (to the `randomList`) a whole array as a one argument. Other way around would be the `apply` method (randomList.apply(this, a)).
Also you probably want to return the "b" array... (I haven't spotted it at the first look) ;)

sono's icon

It's never too late to say thanks... Thanks!