1

I have a perl hash which I'm looping over and building a JavaScript array. The JavaScript array starts out with a length of 0 when I initiate it; however, it quickly grows to 1001 in the first past, 2001 in the second, and 4001 in the third pass. I'm expecting the length to be 3! Here's the code and the perl hash following.

Code

var offers = [];
%  foreach my $amount (keys %$offers) {
     offers['<% $amount %>'] = [];
     console.log(offers.length);
%  }

Perl Hash

{
    '1000'=>{
        '6'=>{
            'payment'=>'173.49',
            'fee'=>'2',
            'APR'=>'13.9'
        },
        '4'=>{
            'payment'=>'256.23',
            'fee'=>'2',
            'APR'=>'11.9'
        }
    },
    '2000'=>{
        '6'=>{
            'payment'=>'346.98',
            'fee'=>'2',
            'APR'=>'13.9'
        },
        '4'=>{
            'payment'=>'512.46',
            'fee'=>'2',
            'APR'=>'11.9'
        }
    },
    '4000'=>{
        '6'=>{
            'payment'=>'693.96',
            'fee'=>'2',
            'APR'=>'13.9'
        },
        '4'=>{
            'payment'=>'1024.92',
            'fee'=>'2',
            'APR'=>'11.9'
        }
    }
};
3
  • Well, that doesn't show anything, JS has a very weird concept of arrays. Try to look at the actual number of indices: var indices; for(key in array){indices.push(key)} console.log(indices.length) Commented May 6, 2013 at 19:07
  • 1
    The first pass does offers[1000] = []. That creates an array whose length is 1001, since it consists of indices 0 through 1000. Maybe you should be using an object instead of an array. Commented May 6, 2013 at 19:09
  • @Barmar, how would use advise converting this has to an object? Using JSON encode in Perl, or manually constructing the object in JavaScript? Commented May 6, 2013 at 21:10

2 Answers 2

1

Try

var offers = [];
%  foreach my $amount (keys %$offers) {
     offers.push('<% $amount %>');
     console.log(offers.length);
%  }
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure this would work, since it needs to be multidimensional.
1

I think what you want is an associative array / object. If you want the data to be identified through code such as offers['1000'] and yet not have 1,000 elements, then you simply need to initialize the offers like this:

var offers = {};

and leave the rest of your code unchanged. There will not be a length property any longer, but you will only be creating one entry rather than 1,000 for each item being stored.

You can iterate through the data by doing like this:

var offer;
for (offer in offers) {
/* do something with offers[offer] here */
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.