syntax for assigning to an array

M

miken32

In PHP, if a function returns an array it's fairly common to capture
its return values like this:

<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>

In Javascript, would the equivalent (acceptable) code be this?

[foo, bar, baz] = some_function_that_return_an_array();

I usually run my code through JSLint as a quick sanity check, but this
expression makes it die. Clearly it's a parsing bug in JSLint, but I
also wanted to make sure that I wasn't doing something completely off
the wall. Thanks.
 
M

miken32

miken32 said the following on 11/27/2007 2:52 PM:
In PHP, if a function returns an array it's fairly common to capture
its return values like this:
<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>
In Javascript, would the equivalent (acceptable) code be this?
[foo, bar, baz] = some_function_that_return_an_array();

var theArray = some_function_that_return_an_array();
alert('theArray is now an array')
I usually run my code through JSLint as a quick sanity check, but this
expression makes it die.

It doesn't die, it generates a message:

Problem at line 1 character 2: Expected a JSON value.
Clearly it's a parsing bug in JSLint,

No it isn't.
but I also wanted to make sure that I wasn't doing something
completely off the wall.

You aren't even in the house to be off the wall :)

Welcome.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptToolbox.com/bestpractices/

I'm using Safari, and if I try to validate this code:

var a, b, c, d = 'one two three';
[a, b, c] = d.split(' ');

I get "Problem at line 151 character 13: Undefined value"

May just be a problem with my browser's JS engine I guess.
 
K

Kailash Nadh

miken32 said the following on 11/27/2007 2:52 PM:
In PHP, if a function returns an array it's fairly common to capture
its return values like this:
<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>
In Javascript, would the equivalent (acceptable) code be this?
[foo, bar, baz] = some_function_that_return_an_array();
var theArray = some_function_that_return_an_array();
alert('theArray is now an array')
It doesn't die, it generates a message:
Problem at line 1 character 2: Expected a JSON value.
No it isn't.
You aren't even in the house to be off the wall :)


--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptToolbox.com/bestpractices/

I'm using Safari, and if I try to validate this code:

var a, b, c, d = 'one two three';
[a, b, c] = d.split(' ');

[] is for carrying the values of an array really.
eg: var a = [1,2,3];

I don't think there is a shorthand for what you are trying to do,
unless ofcourse, you'd use a[0], [1].. instead of a,b,c.. OR assigning
the values manually to the variables after the split()
 
R

Richard Cornford

You have posted this PHP to a javascript group without any explanation as to what it is actually
doing. It is not very relational to assume that people who know javascript will also know PHP.
Would you make that assumption the other way around? Saying things like "capture its return
values" doesn't really help. In javascript terms a function/method call that "returns an array"
returns a single value and that value is the array object. If you want that array you assign the
value to a variable or the property of an object, giving you a variable or property of an object
that refers to an array object.

I'm using Safari, and if I try to validate this code:

"Validate"? Do you mean execute?
var a, b, c, d = 'one two three';
[a, b, c] = d.split(' ');

That last line is just a syntax error. The - [a, b, c] - is an Array literal (defines an array
object with 3 elements containing, in tern, the values of the local variables a, b and c (which
are all the undefined value at this point)). The evaluation of the Array literal results in a
value, and there is no sense in which assigning another value to a value can work, and it is
also forbidden by the syntax rules.
I get "Problem at line 151 character 13: Undefined value"

But don't intend letting on to us which line line 151 is.
May just be a problem with my browser's JS engine I guess.

An error is inevitable because of the syntax error in the code, which error (in terms of the
exact wording) will depend on the JS engine. But I think the error you report is the last error
generated, while it is the first error generate that should always be the first error addressed
(as all subsequent errors may be a direct consequence of the first).

Richard.
 
M

miken32

miken32 said the following on 11/27/2007 3:58 PM:


miken32 said the following on 11/27/2007 2:52 PM:
In PHP, if a function returns an array it's fairly common to capture
its return values like this:
<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>
In Javascript, would the equivalent (acceptable) code be this?
[foo, bar, baz] = some_function_that_return_an_array();
var theArray = some_function_that_return_an_array();
alert('theArray is now an array')
I usually run my code through JSLint as a quick sanity check, but this
expression makes it die.
It doesn't die, it generates a message:
Problem at line 1 character 2: Expected a JSON value.
Clearly it's a parsing bug in JSLint,
No it isn't.
but I also wanted to make sure that I wasn't doing something
completely off the wall.
You aren't even in the house to be off the wall :)
Thanks.
Welcome.
I'm using Safari, and if I try to validate this code:
var a, b, c, d = 'one two three';
[a, b, c] = d.split(' ');

<sigh> I give you code to do exactly what you want and you still try to
fubar it.

var myArray = d.split(' ');

Now, myArray is an array that you wanted. You need to stop thinking PHP
and start learning the JS way if you want to write JS.
I get "Problem at line 151 character 13: Undefined value"
GIGO.

May just be a problem with my browser's JS engine I guess.

No, it is a major problem with your code.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptToolbox.com/bestpractices/

I understand that's not the way to do it, no need for sarcasm and
sighs!

I was reposting similarly incorrect code to highlight the parsing
error in JSLint; I guess I wasn't clear enough, but the error message
was coming from JSLint, not my browser. Clearly if I'm validating 2
lines of JS and it reports an error on line 151 something's wrong, and
I'll send an email to alert him to the problem.

And I promise with all my heart that I will take the extra lines of
code to explicitly assign elements of the returned array to variables.
Thanks.
 
S

slebetman

In PHP, if a function returns an array it's fairly common to capture
its return values like this:

<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>

In Javascript, would the equivalent (acceptable) code be this?

[foo, bar, baz] = some_function_that_return_an_array();

As others have replied, and you have found out for yourself by trying
to run this in a browser, that's not valid javascript. The acceptable
equivalent is:

var tmp = some_function_that_return_an_array();
foo = tmp[0];
bar = tmp[1];
baz = tmp[2];

However, you can emulate a similar functionality with a Tcl style
syntax rather than PHP's Perl style syntax:

function assign (thearray) {
for (var i=1; i < arguments.length; i++) {
eval (arguments + '=' + thearray[i-1])
}
}

# The syntax to use this would be:

assign(function_return_array(), 'foo', 'bar', 'baz');
 
R

Richard Cornford

Randy said:
Richard Cornford said the following on 11/27/2007 5:09 PM:


Typically, and in experience, the first error reported is
usually the first error encountered. Do you know of a UA
that will report the last error encountered instead of
the first error?

I know of at leas some browsers where the report of one error is replaced by the report of the
next, and so when everything grinds to a halt and someone looks at the errors reported they are
actually looking at the last error (and usually an active 'back' button that can be used to look
at the previous errors).

The syntax error in the code posted would not produce the error reported, but the error reported
could easily be the consequence of the syntax error stopping the compiling of all the SCRIPT
contents where it appeared.

Richard.
 
T

Thomas 'PointedEars' Lahn

slebetman said:
In PHP, if a function returns an array it's fairly common to capture
its return values like this:

<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>

In Javascript, would the equivalent (acceptable) code be this?

[foo, bar, baz] = some_function_that_return_an_array();

As others have replied, and you have found out for yourself by trying
to run this in a browser, that's not valid javascript. [...]

That depends how you understand "javascript". JavaScript 1.7 as implemented
in Gecko 1.8.1 (Firefox 2 etc.) allows this:

http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Destructuring_assignment


PointedEars
 
S

slebetman

Randy Webb said the following on 11/27/2007 6:27 PM:
slebetman said the following on 11/27/2007 5:57 PM:
function assign (thearray) {
for (var i=1; i < arguments.length; i++) {
eval (arguments + '=' + thearray[i-1])

arguments = thearray[i-1]


Although that should be:

window[arguments] = thearray[i-1];


That only works for global variables. Wouldn't work for local
variables. Using 'eval' is the only way I can think of doing it:

function testme () {
var x;
var y;
assign([1,2,3,4],'x','y');
}
 
B

Bruno Desthuilliers

miken32 a écrit :
In PHP, if a function returns an array it's fairly common to capture
its return values like this:

<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>

<ot>
For those that don't know PHP:

list($a, $b, $c) = array(1, 2, 3);

is equivalent to:

$x = array(1, 2, 3);
$a = $x[0];
$b = $x[1];
$c = $x[2];

In Javascript, would the equivalent (acceptable) code be this?

[foo, bar, baz] = some_function_that_return_an_array();

No. There's no such thing in javascript. Anyway, if the ordering in your
array is signifiant (ie: your array is really a tuple, IOW an
index-based record), then you should consider returning an object instead:

var obj = someFuncThatReturnsAnObj();
alert(obj.foo + "\n" + obj.bar +"\n" + obj.baaz);

Even if you can't modify some_function_that_return_an_array, you can at
least wrap it:

function someFuncThatReturnsAnObj() {
var ar = some_function_that_return_an_array();
return {
foo: ar[0],
bar: ar[1],
baaz: ar[2]
};
}

HTH
 
B

Bruno Desthuilliers

Randy Webb a écrit :
(snip -lost explanations about PHP's list() function)
And all this time, I just referred to the entry in the array I wanted. I
could see a possible benefit of it but not entirely sure I would ever
use it in JS.

<ot mode='again'>

Python has a similar (yet a bit cleaner IMHO) concept named 'tuple
unpacking', which let you emulate "multiple return values":

def some_func():
return 1, 'toto', 42

id, name, age = some_func()


It's also handy for value swapping:

a = 1
b = 2

a, b = b, a

</ot>

And FWIW, I'd certainly use it in javascript too if it was available !-)
 
V

VK

In PHP, if a function returns an array it's fairly common to capture
its return values like this:

<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>

In Javascript, would the equivalent (acceptable) code be this?

[foo, bar, baz] = some_function_that_return_an_array();

[args] in JavaScript is an implicit Array constructor call.
Constructor call cannot be left-hand side of the assignment, so this
PHP feature borrowed from Perl is not available in JavaScript: or so I
thought till now...

In this code snippet:
var foo,bar,baz;
try {
[foo, bar, baz] = [1,2,3];
alert(foo);
}
catch(e) {
alert(e.number & 0xFFFF);
}

IE reports - totally correct - run-time error error 5008 "Illegal
assignment".

To my huge surprise Firefox is all happy with that with foo, bar, baz
initiated with the respective values of the anonymous array, just like
there is not ECMA anymore but all Perl around.

It is funny that for say
new Array('foo') = new Array(1);
Gecko gets back the reality/standards and reports "illegal assignment
left-hand side". Well, thanks for that at least...

Evidently some of Gecko JavaScript engine developers came from Perl/
PHP grounds so it just added a feature he used so do to not be
bothered with language/standards differences.
 
S

slebetman

In PHP, if a function returns an array it's fairly common to capture
its return values like this:
<?php
list($foo, $bar, $baz) = some_function_that_return_an_array();
?>
[snip]

In this code snippet:
var foo,bar,baz;
try {
[foo, bar, baz] = [1,2,3];
alert(foo);
}
catch(e) {
alert(e.number & 0xFFFF);
}

IE reports - totally correct - run-time error error 5008 "Illegal
assignment".

To my huge surprise Firefox is all happy with that with foo, bar, baz
initiated with the respective values of the anonymous array,

Which is also totally correct (read on..)
Evidently some of Gecko JavaScript engine developers came from Perl/
PHP grounds so it just added a feature he used so do to not be
bothered with language/standards differences.

Not really from Perl. (OK, yes from Perl but it's valid Javascript).
As Thomas mentioned it's actually from Javascript 1.7 / ECMAScript 4.
Unfortunately no other browser apart from Firefox currently implements
Javascript 1.7.
 
S

slebetman

slebetman said the following on 11/28/2007 4:11 AM:


Randy Webb said the following on 11/27/2007 6:27 PM:
slebetman said the following on 11/27/2007 5:57 PM:
<snip>
function assign (thearray) {
for (var i=1; i < arguments.length; i++) {
eval (arguments + '=' + thearray[i-1])
arguments = thearray[i-1]
Although that should be:
window[arguments] = thearray[i-1];

That only works for global variables.

True, but, it is reliable. See below.
Wouldn't work for local variables.

True again.
Using 'eval' is the only way I can think of doing it:

Did you test it? FF2, IE7, Opera9 all give undefined for the alerts below.


Admittedly I didn't test it when I wrote it.
function testme () {
var x;
var y;
assign([1,2,3,4],'x','y');

alert(x)// undefined
alert(y)// undefined

Test code:

function assign (thearray) {
for (var i=1; i < arguments.length; i++) {
eval (arguments + '=' + thearray[i-1])
}}

function testme () {
var x;
var y;
assign([1,2,3,4],'x','y');
alert(x)
alert(y)}

testme()



Hmm.. strange. I just tested it right now in IE6, Firefox, Opera9 and
Safari and it works. I don't know why it fails on your machine.

Here's my test file which works:

<script>
function assign (thearray) {
for (var i=1; i < arguments.length; i++) {
eval (arguments + '=' + thearray[i-1])
}
}

function testme () {
assign([1,2,3,4],'x','y','z');
alert(y);
alert(z);
}

testme();

/* Not much different from yours so I'm
* not sure why yours isn't working.
* As for why you'd want something like
* this, well.. some people like syntactic
* sugar others have different tastes.
*/
</script>
 
V

VK

That depends how you understand "javascript".

As some ECMAScript-compliant (up to the best of authors' talents)
implementation. ECMAScript specs allow extensions and even extra
keywords. At the same time it doesn't assume that someone will make a
totally different language, still call it "JavaScript" and start
parsing <script> blocks by the rules of such language. No one language
spec goes so far - and for some good I guess. Other words one may add
someVeryCoolMethod to Global and it's OK, just document it properly.
From the other side one cannot say allow "this" or constructor itself
to be in the left-hand side of assignment just because someone's hands
are overly itchy tonight. For itchy hands of this kind there is
project manager to hit by his stick on time. Starting from Gecko
JavaScript 1.6 and especially 1.7 I'm getting more and more
disappointed by the engine project manager up to the point to start
wondering if there is one at all...

Just makes my points. "JavaScript sucks, I'm used to PHP (Perl) with
is cool, so I'll call it Destructuring_Assignment and kiss my a**".
 
V

VK

http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Destructuring_assignment
Just makes my points. "JavaScript sucks, I'm used to PHP (Perl) with
is cool, so I'll call it Destructuring_Assignment and kiss my a**".


http://developer.mozilla.org/en/docs/New_in_JavaScript_1.7#Using_JavaScript_1.7

"In order to use some of the new features of JavaScript 1.7, you need
to specify that you wish to use JavaScript 1.7. In HTML or XUL code,
use:
<script type="application/javascript;version=1.7"/>
"

Uhm... Did we use this type? I see that not but 1.7 is still in all
its "beauty"

I hope Mozilla at least will issue some small warning at the day then
they will decide to remove .prototype property from objects or
something equally revolutionary.
 
S

slebetman

As some ECMAScript-compliant (up to the best of authors' talents)
implementation. ECMAScript specs allow extensions and even extra
keywords. At the same time it doesn't assume that someone will make a
totally different language, still call it "JavaScript"..

Not a "totally different language" per se. Javascript 1.7 only updates
Javascript to include most of the features of the latest ECMAScript
spec. This is actually fully valid ECMAScript 4. ECMAScript 4 is still
currently in draft/proposal mode but I don't see much objections to
the proposal so far so it's on track for formal approval. AFAIK the
only two languages based on ECMAScript that have been updated to
include ECMAScript 4 features are Javascript 1.7 and Actionscript 3
(Flash/Flex, though Actionscript3 doesn't support array
destructuring).
 
S

slebetman

slebetman said the following on 11/28/2007 11:14 AM:
slebetman said the following on 11/28/2007 4:11 AM:
function testme () {
var x;
var y;
assign([1,2,3,4],'x','y');
alert(x)
alert(y)}
testme()
Hmm.. strange. I just tested it right now in IE6, Firefox, Opera9 and
Safari and it works. I don't know why it fails on your machine.

Because you changed the code.
function testme () {
assign([1,2,3,4],'x','y','z');
alert(y);
alert(z);
}

Compare the two. The difference in the two is monumental.

Crap.. yeah, just realised my code actually doesn't work with local
vars as well. Sorry.. guess the OP will have to go with the more
traditional method.
 
B

beegee

Python has a similar (yet a bit cleaner IMHO) concept named 'tuple
unpacking', which let you emulate "multiple return values":

def some_func():
return 1, 'toto', 42

id, name, age = some_func()

Ruby, same thing:

id, name, age = some_func_that_returns_an_array()

Yup, I wish it existed in Javascript too.

Bob
 
T

Thomas 'PointedEars' Lahn

VK said:
That depends how you understand "javascript".

As some ECMAScript-compliant (up to the best of authors' talents)
implementation. ECMAScript specs allow extensions and even extra
keywords. [...]

Unsurprisingly, you missed the point completely.
Just makes my points. "JavaScript sucks, I'm used to PHP (Perl) with
is cool, so I'll call it Destructuring_Assignment and kiss my a**".

Don't drink and post.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top