Sami El Hilali Sami El Hilali - 2 months ago 19
PHP Question

PHP equivalent of list and explode in javascript


Possible Duplicate:

Javascript equivalent of PHP’s list()




I want an equivalent of this line but in JavaScript :

<?php list($Id, $Iduser, $Idmany) = explode("," , $IdALL); ?>


Where :

$IdALL = '1, 2, 3';


Is there any way to do that with JavaScript and that could be supported on all modern browsers ?

Answer
var values = "1, 2, 3".split(", ");
var keys = ["Id", "Iduser", "Idmany"];
var final = {};

for(var i = 0; i < values.length; i++){
    final[keys[i]] = values[i];
}

Of course, at the expense of readability you could do all this in the for statement:

for(var i = 0, values = "1, 2, 3".split(", "), keys = ["Id", "Iduser", "Idmany"], final = {}; i < values.length; i++){
    final[keys[i]] = values[i];
}

The variables can then be accessed as follows:

alert(final.Id);
alert(final.Iduser);
alert(final.Idmany);