rbradshaw
rbradshaw

Reputation: 35

Compare array variables

when trying to run the following code:

var pvals = new Array();
pvals = "[" + $("#upcheck").val() + "]";
pvals = $.parseJSON(pvals);
pvals = pvals.sort(function(a,b) { return parseFloat(a.id) - parseFloat(b.id) } );

for (var i = 0; pvals.length; i++) {
    if (i == 0) {
       //do something
    } else {
        if (pvals[i].id == pvals[i - 1].id) {
            //do something
        } else {
            //do something else
        }
    }
}

Firebug within Firefox shows the following message "TypeError: pvals[(i - 1)] is undefined" Can anyone please help? I have defined pvals as an array.

Thanks

Ryan

Upvotes: 0

Views: 92

Answers (3)

Sunny Patel
Sunny Patel

Reputation: 8077

The way you define pvals doesn't work. You need to escape the quotes.

pvals = '[{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}]';

Alternatively, just use it as an array, and forget the JSON.parse():

pvals = [{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}];

Also, your for loop doesn't end unless pvals.length becomes 0 or false. You should change that line to for (var i = 0; i < pvals.length; i++) {, which will fix your undefined error since you were trying to access an array index that was out of bounds.

Edit: The last statement still holds true based on OP's edited question.

Upvotes: 0

000
000

Reputation: 27247

It doesn't make a bit of sense to write json as a string, then immediately parse it.

Rather than using JavaScript Object Notation as a string, just notate the object in javascript.

pvals = [{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}];

Upvotes: 1

juvian
juvian

Reputation: 16068

This should work:

pvals = '[{"id": "3", "field": "name", "previous": "john"},{"id": "3", "field": "ext", "previous": "1234"},{"id": "2", "field": "name", "previous": "bill"}]';

Also:

for (var i = 0; i<pvals.length; i++) { // if not loop doesnt stop

Upvotes: 1

Related Questions