5

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 ?

Community
  • 1
  • 1
Sami El Hilali
  • 981
  • 3
  • 12
  • 21
  • JavaScript 1.7 has [destructuring assignments](https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7#Destructuring_assignment_%28Merge_into_own_page.2Fsection%29) but only gecko has any real implementation of JavaScript 1.7 and [webkit behaves badly](https://bugs.webkit.org/show_bug.cgi?id=23097). – Paul S. Dec 01 '12 at 11:34
  • @MuthuKumaran That just blows my mind. I hope it becomes widely supported soon. – Asad Saeeduddin Dec 01 '12 at 11:37

3 Answers3

7
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);
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
1

No, JavaScript currently has no equivalent of the list construct (which is called a "destructuring assignment"). You have to assign the variables individually. ES.next may very well have something for this, but not the current ES5 (or ES3 on older browsers).

So the best you could do is a bit more awkward:

var idAll = "1, 2, 3";
var parts = idAll.split(/\s*,\s*/);
var id = parts[0];
var idUser = parts[1];
var idMany = parts[2];

Note that the IDs will be strings; if you want them to be numbers, you'll have to parse them (parseInt is one option, putting a + in front of parts[0] et. al. is another; this answer goes into details).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Please see the site: http://phpjs.org/functions/

Here you want all the functions available in php to js.

Chirag Patel
  • 516
  • 4
  • 14
  • 1
    This cannot be done even with stuff from that site. JavaScript doesn't have the necessary language structure to allow you to assign multiple variables at the same time (and it would require language support, you can't just write a function to do it). – T.J. Crowder Dec 01 '12 at 11:34
  • 1
    This doesn't answer the question. I couldn't find `list` function from your link. – Muthu Kumaran Dec 01 '12 at 11:40
  • @Muthu Please list() implementation in Javascipt please follow the link : http://solutoire.com/2007/10/29/javascript-left-hand-assignment/ – Chirag Patel Dec 03 '12 at 05:44