0

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?

1
  • 2
    You misspelled length in the 3rd line of your code. Does that error exist in your actual code as well? Also - what's the point of this? Commented Mar 10, 2011 at 21:22

1 Answer 1

3

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".

Sign up to request clarification or add additional context in comments.

1 Comment

"a"/"arr" is copy/paste error, it is correct in the source, but damn i misspelled length. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.