1

I have an interesting problem with a map that is broken in Firefox. When I test if an empty map has the string "watch" it will return true and return the function watch(). I want that to return false since I haven't added the key "watch" to the map. A quick example

I normally create a basic map like

var myMap = {}
myMap["apple"] = 1;
myMap["pear"] = 2;

And to test if the map has the object I would write

if ("apple" in myMap) { ... }

And the problem is when I want to add the string "watch" to the map if the map doesn't all ready contain it. So when I check to see if the map contains "watch" it returns true.

if ("watch" in myMap) { ... }
// This also returns true.  and returns the function watch()

Any ideas on how to avoid this behaviour?

Thanks

1
  • 3
    Objects have built in properties, Object.watch being one of them, use a property name that isn't already in use, and it solves itself. Commented Jan 7, 2014 at 16:01

2 Answers 2

2

It's because an object literal inherits from the Object prototype. You can create an empty object, that inherits from nothing:

var myMap = Object.create(null);

Or check with hasOwnProperty:

if (myMap.hasOwnProperty('watch')) {
  ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. creating the empty object is what I needed to do.
2

You can try

var myMap = {};
myMap["apple"] = 1;
myMap["pear"]=2;

if (myMap.hasOwnProperty("apple")) {

}

if (myMap.hasOwnProperty("watch")) {

}

Comments

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.