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');
}

      

+3


source to share


5 answers


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');
}
      

Run codeHide result


+2


source


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.

+2


source


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');
}

      

+1


source


var element = [];

element['obj'] = 'one';

if ( typeof element['obj']['bg'] === 'undefined' ) {

    console.log('not defined');

    element['obj'] = {'bg':'red'};

    console.log("My value:"+element['obj']['bg'] );

} else {
    console.log('defined');
}

      

http://jsfiddle.net/o66uhd05/3/

+1


source


You can try this way.

var element = [],item = [];

item['obj'] = 'one';
element.push(item);

if ( typeof element['obj']['bg'] === 'undefined' ) {

    console.log('not defined');

    item['bg']='red';

    element.push(item);

    console.log( element);

} else {
    console.log('defined');
}

      

0


source







All Articles