tags:

views:

151

answers:

3

I am migrating an asp code to .net. I came across the following code but not sure what is it doing.

var collection = {};
if (typeof(collection["null"]) != "undefined" && 
    typeof(collection["null"][id]) != "undefined")

Can any well tell that what does collection["null"] does? If possible, how to define it in .Net

Just to give an idea, I made closedMealArea as a List in .Net

Thanks in advance

Cheers, wildanjel

+2  A: 

In JavaScript, collection["null"] returns the property with the name "null" that is owned by the object collection. collection.null is equivalent to collection["null"].

Soubok
dangerous use of the word "property" there. Everything in js is effectively a hashmap. Yes it could be a "property" of an object, but it could also be an array indexer
Andrew Bullock
In JS, string indexes are properties. "Arrays" with string indexes are in fact Objects.
Fabien Ménager
"collection.null is equivalent to collection["null"]." except that I don't believe collection.null is valid javascript.
Breton
({'null':123}).null // is a valid expression and is 123
Soubok
typeof null # object, typeof window.null # undefined :)
Kent Fredric
A: 

It's just an array item.

stoimen
+2  A: 

All the above are correct, in some way. Javascript uses two different ways of accessing properties/method on an object, or items in what is effectively its version of an associative array. As mentioned by Soubok, they are object['propOrMethodName'] and object.propOrMethodName. They are equivalent.

Even a standard Array, with integer indices, can have named properties/methods. Javascript really makes no distinction on the whole. What you can't do, though, is nonArrayObject[n] or arrayObject.n where n is an integer.

In the case of the question, though, collection is explicitly an object:

var collection = {};

An array, with integer indices, would be declared thus:

var collection = [];

As the latter statement tests collection["null"][n] (assuming n is again an integer), I'd say that collection is intended to have a series of properties, each of which is an Array. One of those properties is named "null".

Matt Sach
Actually, yes, you can do: var obj = {}; obj[3] = 42;
Ates Goral
Oops, yes, my bad. The gotcha there is that you have a non-array object with a property named "3", but you can't use obj.3 to access it and obj.length === undefined. However, obj[3] and obj['3'] both give the correct value.
Matt Sach