Does JavaScript have a language construct or something similar to the php list command? http://php.net/manual/en/function.list.php
This command will assign the values of an array to variables in a single statement. For example, given the array:
$info = array('Coffee', 'brown', 'caffeine');
The list command will assign each of the array element values to named variables:
list($drink, $color, $power) = $info;
such that:
echo "$drink is $color and $power makes it special."; // results in: Coffee is brown and caffeine makes it special.
So this is an easy way to assign values to many variables in one statement.
Does JavaScript have something equivalent where each variable does not have to be assigned separately?
Is there a way to do this using either an object’s properties or an array’s elements? If not, can a function be written that would do it? If the only way to do this is via a function, then the function would need access to the scope where the variables are defined.
I tried the solutions in this five year old question: Javascript equivalent of PHP’s list(), but they don’t work. The Array prototype change fails to assign the variables in my node.js environment and the left handed array assignment is a reference error in Chrome. There is talk about an experimental new technique, but the talk is several years old. I’d like to know if there is a solution to this better than those listed in the linked question.
Advertisement
Answer
I’ve just written a simply function, and it works. Just not exactly like list in php. Here it is
function list(fn,array){ if(fn.length && array.length){ for(var i=0;i<array.length;i++){ var applyArray = []; for(var j=0;j<array[i].length;j++){ fn[j] = array[i][j]; applyArray.push(fn[j]); } fn.apply(this,applyArray); } } }
It’s nothing spectacular but if you are looking for something simple and use case for yourself there it is.
How to use this?
//array array mixture for composure var arrayMixture = [ ["coffee","sugar","milk"], ["tea","sugar","honey"] ]; //call our function list(function(treat,addin,addin2){ console.log("I like "+treat+" with " + addin + " and " + addin2); },arrayMixture); //output: //I like coffee with sugar and milk //I like tea with sugar and honey
Hope that’s what you were looking for