My code:
var a = "1",
b = "hello",
c = { "100" : "some important data" },
d = {};
d[a]["greeting"] = b;
d[a]["data"] = c;
console.debug (d);
I get the following error:
Uncaught TypeError: Cannot set property 'greeting' of undefined.
I'm trying to do something similar to an associative array. Why isn't this working?
The "Cannot set properties of undefined" error occurs when setting a property on an undefined value. To solve the error, conditionally check if the value is of the expected type (object or array) or has to be initialized before setting the property on it.
To solve the "Cannot read properties of undefined" error, make sure that the DOM element you are accessing exists. The error is often thrown when trying to access a property at a non-existent index after using the getElementsByClassName() method. Copied! const boxes = document.
The undefined property indicates that a variable has not been assigned a value, or not declared at all.
JavaScript TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function. This error occurs in Chrome Browser when you read a property or call a method on an undefined object .
you never set d[a]
to any value.
Because of this, d[a]
evaluates to undefined
, and you can't set properties on undefined
.
If you add d[a] = {}
right after d = {}
things should work as expected.
Alternatively, you could use an object initializer:
d[a] = {
greetings: b,
data: c
};
Or you could set all the properties of d
in an anonymous function instance:
d = new function () {
this[a] = {
greetings: b,
data: c
};
};
If you're in an environment that supports ES2015 features, you can use computed property names:
d = {
[a]: {
greetings: b,
data: c
}
};
You have to set d[a]
to either an associative array, or an object:
d[a] = [];
d[a] = {};
Without setting, this is what's happening:
d[a] == undefined
, so you're doing undefined['greeting']=b;
and by definition, undefined has no properties. Thus, the error you received.
The object stored at d[a]
has not been set to anything. Thus, d[a]
evaluates to undefined
. You can't assign a property to undefined
:). You need to assign an object or array to d[a]
:
d[a] = [];
d[a]["greeting"] = b;
console.debug(d);
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