0

I have the following code...

function foo(type) {
    if(foo.type == undefined) foo.type = 0;
}

What I'd like it to do is create a new property on the foo object for each "type" that comes through and set that property to zero (and later begin counting each time a "type" comes through). However, I hit a mental blip, in this case foo.type is probably evaluated as the property type, on foo and not whatever the variable type refers to.

I need to convert the value of type to a property, any ideas?

And yes I know this question's name sucks, if you think of something better just edit the quesiton.

4

2 回答 2

3
function foo(type) {
    if(foo[type] == undefined) foo[type] = 0;
}

您可能想要使用=== undefined,这样您就不会得到任何意外的结果

于 2013-07-17T00:33:00.050 回答
2
if (typeof foo[type] === 'undefined') {
    foo[type] = 0;
}
于 2013-07-17T00:33:06.390 回答