while(var row = fn());

Is there any equivalent metod to make like an php mysql_fetch_array while loop in js?

in php you can do:

<?php
while ($row = mysql_fetch_array($result)) {
    echo "my name is " . $row['name'] . " and i'm " . $row['age'] . " yeas old";
}
?>

i have this object/array:

function fetch_array(arr) {
    // My magic fn that dose not work well, b/c it change the orginal refence
    return arr.shift();
}
var result = [{
    name: "Bob",
    age: 12
}, {
    name: "Jim",
    age: 18
}]

// And want to do:


while (row = fetch_array(result)) {
     alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
 }

// returns zero :(​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ dont want that
console.log(result.length);

Array.shift removes the first element of the array, so when you're done looping through it like that, it's empty.

If all you want to do is to go through it and use the data, try this:

var row;
for (var i = 0, l = result.length; i < l; i++) {
    row = result[i];
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
}

// returns 2
console.log(result.length);

or change the fetch_array function to this, and leave the rest as it is:

var index = 0;
function fetch_array(arr){
   return arr[index++]; 
}

You would have to reset the index variable to 0 if you wanted to loop through it again though.

You have the array item available in your loop so you could always recreate it if you wanted. Or just copy it before you use your fetch_array function.

Alternatively just loop through the array.

Depending on what browsers joy want to support, array.forEach could be an option:

result.forEach(function(row) {
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
});

Or if you use jQuery:

$(result).each(function() {
    var row = this;
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " years old");
});

I changed your fetch_array function in this way

function fetch_array(arr) {
   var i = fetch_array.i || 0;
   fetch_array.i = ("undefined" === typeof arr[i])? 0 : i + 1;
   return arr[i]; 
}

and this leave untouched your array. The idea is to attach and increment an index property to the the function itself

Edit: I had to reset the index when the end of array is reached, otherwise you would not be able to loop more than once on the same (or different) «resultset», e.g.

while(row = fetch_array(result)){
    alert("my name is " + row["name"] + " And I'm " + row['age'] + " yo");
}

while(row = fetch_array(result)){
   alert("here again the name " + row["name"] + " and age: " + row['age']);
}

console.log(result.length); // returns 2;

as aside note, the condition to reset the index could be also done with

fetch_array.i = (i === arr.length)? 0 : i + 1;