JavaScript Array - Uncaught TypeError: Unable to 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++)

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

        // 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) {
var res = shuffle(resultArray);
for (var i=0;i<res.rows.length;i++){


Uncaught TypeError: Cannot read property 'length' of undefined

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

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


therefor use:

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