candlejack
candlejack

Reputation: 1209

JavaScript Array - Uncaught TypeError: Cannot read property 'length'

I'm developing a Cordova/Phonegap application that uses an internal database... Normally I do the query, and then I read the results in this way:

for (var i=0;i<results.rows.length;i++)
{
     name=(results.rows.item(i).name);
     alert(name);
}

Since the RANDOM() SQLite function has been giving me problems, I decided to mess up the results myself:

function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}
var resultArray = [];
for(var x=0; x < results.rows.length; x+=1) {
     resultArray.push(results.rows.item(x));
}
var res = shuffle(resultArray);
for (var i=0;i<res.rows.length;i++){
     name=(res.rows.item(i).name);
}

ERROR:

Uncaught TypeError: Cannot read property 'length' of undefined

Why is this happening? And how I can solve it? thanks!

Upvotes: 3

Views: 3374

Answers (2)

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7169

var res = shuffle(resultArray);
for (var i=0;i<res.length;i++){
     name=(res.item(i).name);
}

if so ?

or better

var res = shuffle(resultArray);
for (var i=0;i<res.length;i++){
     name=(res[i].name);
}

if not - please show what you'v got in console in

var res = shuffle(resultArray);
console.log(res);
for (var i=0;i<res.length;i++){
     name=(res[i].name);
     console.log(res[i]);
}

P.S. and keep in mind, that all value set in single variable 'name' - so they kick each other

Upvotes: 2

dannyde
dannyde

Reputation: 122

you're pushing to resultArray only items without rows, therefor you need to traverse only via the resultArray itself.

resultArray.push(results.rows.item(x));

therefor use:

var res = shuffle(resultArray);
for (var i=0; i < res.length; i++) {
    name = (res[i].name);
}

Upvotes: 1

Related Questions