4 ms·
What's the "correct" ("less funny"?) result of Array(16).join("wat" - 1) + " Batman!" ? Empty strings separated with NaNs look perfectly logical to me (I'
by bgarbiak 15y ago
What's the "correct" ("less funny"?) result of
Array(16).join("wat" - 1) + " Batman!"
?
Empty strings separated with NaNs look perfectly logical to me (I'm a JS guy though, so, well, bear with me).
- Anderkent 15y agoA TypeError.
- weavejester 15y agoThat's probably one of the more logical examples. I'd have expected an exception from any other language, though (Javascript I know doesn't tend to type error).
- antoncohen 15y agoWell, .join(x) joins an array into a string, with x as the separator. First of all what does Array(16) make? Effectively it should make an array with null 16 times. Now, JavaScript seems to think null is a blank string, a string with the text 'null', or a zero depending on the context. The first thing it should do is TypeError that null is not a string. Or don't join null fields because there is nothing there. If is does convert null to '', then it should TypeError on string - int. If it is not going to TypeError it should do something sensible, like slice the string > Array(16).join("wat".slice(0,-1)) + " Batman!" 'wawawawawawawawawawawawawawawa Batman!' I think the correct thing would be to TypeError in two different places. Or change the language so things that don't error actually work. Returning a string with NaNs in it will just lead to uncaught errors. If it actually returns something it should probably be ' Batman!'. JavaScript nuttiness: Now it's zero: > null + 1 1 Now it's "null": > null + "text" 'nulltext' Now it's a blank string: > [null, null, null].join() ',,' Python errors when things don't make sense, and forces you to make them make sense: If it doesn't work, error: >>> "wat" - 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for -: 'str' and 'int' Can't join None into a string: >>> ','.join([None, None, None]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected string, NoneType found Convert None to a string if you want: >>> ','.join([str(i) for i in [None, None, None]]) 'None,None,None' But it makes more sense to drop the None: >>> ','.join([str(i) for i in [None, None, None] if i]) ''