2017-04-19 1 views
0

誰かがこのコードを見ることができますか?明らかにそれらは同等ではない。undefinedをチェックするこの方法はどうしてうまくいかないのですか?

これは私がしたいように振る舞いませんでした私の元のコードでした。基本的に、私が望むのは、変数が定義されている場合にのみ変数を検証することです。ログを無視します。それらはデバッグのためのものでした。 これは予想通り、この作品が期待

let { fullName, email, password } = userInformation; 

    if(email){ 
    console.log("EMAIL IS DEFINED"); 
    if(!validator.isEmail(email)) { 
     errors.email = "Please enter a valid email address"; 
    } 
    } 

    if(fullName){ 
    console.log("FULLNAME IS DEFINED"); 
    if(validator.isEmpty(fullName)){ 
     errors.fullName = "Fullname is required"; 
    } 
    } 

    if(password){ 
    console.log("PASSWORD IS DEFINED"); 
    if(validator.isEmpty(password)){ 
     errors.password = "Password is required"; 
    } 
    } 

として動作しません。それはなぜそうですか?

let { fullName, email, password } = userInformation; 

    if(!email){ 
    console.log("EMAIL IS DEFINED"); 
    if(!validator.isEmail(email)) { 
     errors.email = "Please enter a valid email address"; 
    } 
    } 

    if(!fullName){ 
    console.log("FULLNAME IS DEFINED"); 
    if(validator.isEmpty(fullName)){ 
     errors.fullName = "Fullname is required"; 
    } 
    } 

    if(!password){ 
    console.log("PASSWORD IS DEFINED"); 
    if(validator.isEmpty(password)){ 
     errors.password = "Password is required"; 
    } 
    } 

編集:基本的には何が起こるたいのは、変数がを定義されている場合の検証を実行することです。現在のところ、2番目の例が妥当でない限り、検証していないということです。

+0

最初のアプローチで直面している問題は何ですか? – motanelu

+1

'fullName、email、password'は** undefined **ですね。これが第二の「アプローチ」が機能する理由です。 – evolutionxbox

+0

あなたは右に何の感嘆符が使われているのか知っていますか?ですから、それがうまくいくならば、おそらくuserInformation行の直後に変数を記録しようとすることができます。 – moped

答えて

3

undefinedのチェックでは、の偽物をチェックしていません。 ""は偽です。したがって、0NaNnullundefined、もちろんfalseです。あなたのバリデータを使用することは決してないだろうので、あなたは、その外側ifに入ることは決してないだろう

if(fullName) { 
    console.log("FULLNAME IS DEFINED"); 
    if(validator.isEmpty(fullName)){ 
    errors.fullName = "Fullname is required"; 
    } 
} 

""以来

がfalsyあるuserInformationが値""fullName性質を持っている場合、これは動作しません。 fullNameを確認してください。値は、具体的undefined、であれば、あなたのバリデータをバイパスしたい場合は(プロパティはuserInformationに存在しなかった、またはそれが存在していたが、値undefinedを持っていたので)

は、あなたが具体的にする必要があります。

if (fullName !== undefined) { 
    console.log("FULLNAME IS DEFINED"); 
    if(validator.isEmpty(fullName)){ 
    errors.fullName = "Fullname is required"; 
    } 
} 

あなたはuserInformationはすべてでプロパティを持っている(しかし、それは価値undefinedでそれを持っていた、そして、あなたはそのために特別にチェックする必要がある場合は、バリデータを使用して守らなかった場合にのみ、あなたのバリデータをバイパスしたい場合:

if ("fullName" in userInformation) { // or `if (userInformation.hasOwnProperty("fullName")) {` if you only want an own property 
    console.log("FULLNAME IS DEFINED"); 
    if(validator.isEmpty(fullName)){ 
    errors.fullName = "Fullname is required"; 
    } 
} 
+0

と言っています。私は変数を破壊していると思った?ああ、私は誤解しました。これは今や理にかなっています。ありがとう! – Nate

関連する問題