【问题标题】:Why do i not get a key if it is false in my object如果我的对象中的密钥为假,为什么我没有得到密钥
【发布时间】:2020-02-27 20:44:57
【问题描述】:

我有一个函数从用户的帖子中获取数据并创建一个电子邮件对象。为了确保我没有收到错误,我在尝试将它们分配给新对象之前检查这些值是否存在。我有一些布尔键,如 dflt 和bounce。

 const createEmail = async(element) =>{
            var newEmail = new contacts.typedEmailAddress
            if(element.id == null){
                newEmail.id = uuidv4()
            }
            else
            {
                newEmail.id = element.id  
            }
                    console.log('Value of Bounce: '+ element.bounce)
                    newEmail.type = element.type
                    newEmail.address = element.address
                    if (element.name){
                        newEmail.name = element.name
                        }
                    if (element.otherLabel){
                        newEmail.otherLabel = element.otherLabel
                        }
                    if (element.dflt){
                        newEmail.dflt = element.dflt
                        }
                    if (element.source){
                        newEmail.source = element.source
                    }
                    if (element.bounce){
                        newEmail.bounce = element.bounce
                    }
                    if (element.dnmm){
                        newEmail.dnmm = element.dnmm
                    }

            console.log(JSON.stringify(newEmail))
    return newEmail

    }

当我将流动元素传递给上述代码时

{ id: '99a8da99-4ea9-4c96-92ee-c98571b133b9',
  parentId: 'farm::03590B5F-AC65-45CB-BB87-C53C2EBCE8B9',
  type: 'default',
  address: 'reza@test.com',
  name: 'reza@test.com',
  otherLabel: null,
  dflt: true,
  dnmm: true,
  bounce: false,
  source: 'Intelius' }

这就是我得到的结果

Value of Bounce: false
{"id":"99a8da99-4ea9-4c96-92ee-c98571b133b9","address":"reza@test.com","name":"reza@test.com","type":"default","dflt":true,"source":"Intelius","dnmm":true}

出于索引原因,我需要密钥为真或假,但不确定为什么不创建它为假

【问题讨论】:

标签: javascript node.js


【解决方案1】:

您在设置newEmail.bounce之前的条件中检查element.bounce

基本上

if (false) {
   // Add property
}

你可能想做element.bounce !== undefined

【讨论】:

  • 所以基本上在使用 if (element.bounce) 时,只有当设置值为 true 时才会返回 false 值。
  • 从逻辑的角度来看 if 语句,而不是值。您在问“如果 element.bounce 为真,则添加该属性”。如果element.bounce 的值为“false”,则条件将失败,并且不会添加任何属性。
【解决方案2】:

在分配属性bounce之前删除if即可。

if(bounce)if(bounce==true) 相同

dfltdnmm 执行相同操作,以防您在 false

时需要它们

【讨论】:

  • 删除条件并不能真正解决他的问题。他想检查该属性是否存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-09
  • 1970-01-01
  • 2011-05-23
相关资源
最近更新 更多