JavaScript checks if an array object exists or is undefined
How do I add a new array to an array if it doesn't exist?
i check this link: How to check if array element exists or not in javascript?
but not sure how to promote the new object!
http://jsfiddle.net/zerolfc/o66uhd05/1/
var element = [];
element['obj'] = 'one';
if ( typeof element['obj']['bg'] === 'undefined' ) {
console.log('not defined');
element['obj']['bg'] = 'red';
console.log( element);
} else {
console.log('defined');
}
source to share
var element = [];
defines an array, not an object. To insert a new value into an array, you need to use the method push
:
element.push({'obj' : 'one'});
But I think you don't need to create an array here, just create an object. Declare your object asvar element = {};
A string works the same way element['obj'] = 'one';
, you have an object with a key obj
and a value one
.
When you write element['obj']['bg']
, you are trying to access an object within an object. Therefore, before setting the value, red
you need to create an object:
element['obj'] = {};
element['obj']['bg'] = 'red';
Complete example:
var element = {};
element['obj'] = {};
if (typeof element['obj']['bg'] === 'undefined') {
console.log('not defined');
element['obj']['bg'] = 'red';
console.log(element);
} else {
console.log('defined');
}
source to share
The element is of type string
, not object or array.
Change the specific variable to an array:
var element = {};
element['obj'] = ['one'];
if ( typeof element['obj']['bg'] === 'undefined' ) {
console.log('not defined');
element['obj']['bg'] = 'red';
console.log(element);
} else {
console.log('defined');
}
Or better object:
element['obj'] = {};
element['obj']['id'] = 'one';
Objects string
are immutable objects.
source to share
Try to insert an empty array first;
var element = [];
element['obj'] = 'one';
if ( typeof element['obj']['bg'] === 'undefined' ) {
console.log('not defined');
element['obj'] = [element['obj']];
element['obj']['bg'] = 'red';
console.log( element);
} else {
console.log('defined');
}
source to share