3 ms·
Here's a more plausible example. Let's say you are trying to call one function out of a list of functions. What do you think this code does? function getInde
by lacker 18y ago
Here's a more plausible example. Let's say you are trying to call one function out of a list of functions. What do you think this code does?
function getIndex() {
return 0
}
function f1() {
alert("foo")
}
function f2() {
alert("bar")
}
var intIndex = getIndex()
[f1, f2][intIndex]()
It looks like it should alert "foo", but run it and you get an "intIndex is undefined" error. Good luck debugging that!
The problem is, the javascript rules for continuing lines are that whenever the next character is any of [({+-, the line is assumed to continue. This is generally correct but not always. For comparison, the analogous Python rule is that a line continues either with an explicit \ or when one of [({ has not yet been closed with its pair. The Python rule doesn't lead to any ambiguous cases that I am aware of, because unclosed parentheses would just be invalid syntax.
- timknauf 18y agoInteresting. I've encountered errors in a similar vein, which in retrospect must have been caused by using an anonymous list in a similar way to your example: [f1, f2][intIndex]() The 'solution' seems to be something like var functions = [f1, f2] functions[intIndex]() but that's a big loss for conciseness.
- lacker 18y agoThe most convenient solution is just using a semicolon. If the line continuation rules were the Python ones, this would "just work"....