Auto-enumeration in Javascript
I want to create C type enumerations, values automatically starting from 0.
What is wrong with the following code?function ArrayToEnum(arr)
{
var len = arr.lenght;
en = {};
for(i=0;i<len;i++)
en[arr[i]]=i;
return en;
}
a=['foo','bar'];
b=ArrayToEnum(arr);
console.debug(b.foo);
> Undefined
I expect it to print 0 but instead(at least in Chromium 9.0) this is undefined. If instead of calling the function, I apply the body directly, it works:
var l=a.length;
for(i=0;i<l;i++) b[a[i]]=i;
console.debug(b.foo);
> 0
What is wrong with the 开发者_运维百科function?
If that's your actual code, "length" is misspelled as "lenght" in the third line:
var len = arr.lenght;
I'd expect that to compile, but it would set len
equal to undefined
, which would prevent your loop body from executing at all. That would result in arr.foo
a.k.a. arr["foo"]
being undefined
, as you're seeing in your output.
Also you're passing "arr"
to ArrayToEnum()
when your array in the previous line is called a
, not arr
.
The common theme here is that when you start talking about a variable you haven't defined yet. JavaScript "helpfully" defines it instead of telling you it doesn't exist yet.
I tried it in the Chrome JS console, and I got "reference error" until I fixed the "a"/"arr" problem. Once that was fixed, I got "undefined" as you describe.
When I fixed "lenght", bingo, it prints "0".
精彩评论