简体   繁体   中英

adding object properties with an if statement

so I am trying to add a property to an object if it doesn't already exist in the Object

so my code basically works

Psudo: (if the property doent exist in the object already add it in)

 var names= ["james", "kate", "kara", "milly"];
var storage = {}; 
var testElement = arr.pop(); 
  if(typeof(storage.testElement==='undefined')){  
    storage.testElement = '1';                    
  }
  else{
    storage.testElement = storage.testElement + 1; 
  }
return console.log(storage);

like I said this is sort of working, the output I get from the console log is { testElement: "1"} Where it says 'testElement' i need that to be the same as the item that was "popped" off the end of the array so in this case the last item in the array is "milly" so i need the object to say { milly: 1 } or { milly: "1" } Can anyone tell me how to change it?

Please wrap your variable for the object access in []

storage[testElement]

and change the line to

if (typeof storage[testElement] === 'undefined') {  

otherwise you get the typeof of the comparison.

 var names= ["james", "kate", "kara", "milly"]; var storage = {}; var testElement = names.pop(); if (typeof storage[testElement] === 'undefined') { storage[testElement] = '1'; } else { storage[testElement] = storage[testElement] + 1; } document.write('<pre>' + JSON.stringify(storage, 0, 4) + '</pre>'); 

it should be

if(storage[testElement] === undefined)

and the working code, using hasOwnProperty to check property available or not then use [] notation to add/modify the property

var names= ["james", "kate", "kara", "milly"];
var storage = {}; 
var testElement = names.pop(); 
if(!storage.hasOwnProperty(testElement)){  
    storage[testElement] = '1';                    
}
else{
    storage[testElement] = storage[testElement] + 1; 
}
return console.log(storage);

Here is the fix to get result as you expect.

 var names= ["james", "kate", "kara", "milly"]; var storage = {}; var testElement = names.pop(); if(typeof storage[testElement] === 'undefined'){ storage[testElement] = '1'; } else{ storage[testElement] = storage[testElement] + 1; } console.log(storage); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM