简体   繁体   English

使用if语句添加对象属性

[英]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? 就像我说的那样,我从控制台日志中得到的输出是{testElement:“ 1”}在上面说'testElement'的地方,我需要将其与从末尾“弹出”的项目相同数组,因此在这种情况下,数组中的最后一项是“ milly”,因此我需要对象说{milly:1}{milly:“ 1”}有人可以告诉我如何更改它吗?

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. 否则,你得到typeof的比较。

 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 和工作代码,使用hasOwnProperty检查属性是否可用,然后使用[]表示法添加/修改属性

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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