This one's a long shot...
In Javascript, I was accessing an object attribute that I was certain existed, but I had a typo was in the name of the key, so was returning undefined
and creating a bug.
How can I write code equivalent to the following, but that throws an error because the key does not exist?
var obj = {'myKey': 'myVal'},
val = obj.myKye;
I'm trying to find a solution that doesn't require me writing a wrapper function that I use every time I want to access a member of an object. Is it possible? Is there another, 'stricter' technique in Javascript for accessing object attributes?
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc.
You can't...
If you want to be very careful hasOwnProperty will let you check if property is defined.
function GetSafe(obj, propertyName)
{
if (obj.hasOwnProperty(propertyName)) return obj[propertyName];
return "Unknown property:"+ propertyName; // throw or some other error reporting.
}
var obj = {'myKey': 'myVal'};
alert(GetSafe(obj, "myKey"));
alert(GetSafe(obj, "myKye"));
Try this:
function invalidKeyException(message) {
this.message = message;
this.name = "invalidKeyException";
}
var obj = {'myKey': 'myVal'},
val = obj.myKye;
if (val == undefined)
throw new invalidKeyException("Key does not exist.");
JSFiddle: http://jsfiddle.net/r2MM4/
(Look at the console)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With