首页 > 解决方案 > 空检查对象不起作用

问题描述

我正在尝试检查空值,即使我知道这些值为空,循环仍然不会中断。为任何帮助而欢呼

constructor(){
    super();
    this.state = {
        warningMsg: 'No Warnings'
    }
    this.detail = {
        name: null,
        phone: null,
        email: null,
        location: null,
        extraDetail: 'Default' 
    }
}

handleSubmit(){
    const {DetailStore} = this.props;

    for (let value in this.detail) {
        console.log(value)
        if (value === null) {
            console.log('null found'); // i should see this in console but i don't
            this.setState({warningMsg:'Check Input'});
            break;
        }
    }
    DetailStore.entDetail(this.detail);
    console.log(DetailStore.getDetail,'Submitted'); 
}

标签: javascriptecmascript-6

解决方案


for..in loops iterate over the property names of the object, not the value of the property. If you want to iterate over object values, better to use Object.values instead:

if (Object.values(this.detail).some(value => value === null)) {
  console.log('null found');
  this.setState({warningMsg:'Check Input'});
}

推荐阅读