[Javascript] Object Not Defined
Terry Riegel
riegel at clearimageonline.com
Sat Nov 12 09:51:46 CST 2011
I think this problem would be nice to have some sort of generalized
helper function. Perhaps...
if( exist(a.b.c.d.e.f) )
All the solutions I have seen seem to be long and error prone.
Terry
On Nov 11, 2011, at 2:13 PM, Hassan Schroeder <hassan at webtuitive.com> wrote:
> On 11/11/11 10:15 AM, Brian L. Matthews wrote:
>
>> The syntax works, but in the first case, if either a or a.data is undefined, it will result in a
>> JavaScript error.
>
> Ah, got it; how about
>
> var foo = function(a){
> try{ result=a.data.items }catch(err){ result=[] }; return result;
> }
>
> Probably not much of an improvement over the original looks-wise :-)
>
> Alternatively, I cheated a bit by writing the equivalent function
> in CoffeeScript, which (like Ruby) allows specifying a default value
> for arguments, and seeing what it got translated to:
>
> foo = ( a = {data: {}} ) -> a.data.items || []
>
> which becomes this (compiled/pretty-printed) JavaScript:
>
> var foo;
>
> foo = function(a) {
> if (a == null) {
> a = {
> data: {}
> };
> }
> return a.data.items || [];
> };
>
> ( using http://jashkenas.github.com/coffee-script/ )
>
> FWIW,
> --
> Hassan Schroeder ----------------------------- hassan at webtuitive.com
> webtuitive design === (+1) 408-621-3445 === http://webtuitive.com
> http://about.me/hassanschroeder
> twitter: @hassan
> dream. code.
> _______________________________________________
> Javascript mailing list
> Javascript at lists.evolt.org
> http://lists.evolt.org/mailman/listinfo/javascript
More information about the Javascript
mailing list