Logical Product Does Not Return True in javascript [Closed]

Asked 1 years ago, Updated 1 years ago, 116 views

This question appears to be outside the scope defined in Help Center for stack overflow.

Closed 5 years ago.

5 years ago

This is a basic question, but please let me know.
Consider the function checkAttr() that gets the following date and returns the format xxxx-yy-zz:

 'use strict'
// setDate
setDate() 
function setDate(){
  valid day = new Date();
  var str = checkAttr(String(today.getFullYear())), String(today.getMonth()+1), String(today.getDate()));
  console.log(str)
}

function checkAttr(a,b,c){
  if(b.length===1&c.length===1){
    console.log("Hoi")
    b = "0" + b;
    c = "0" + c;
  } else if(b.length===1){
    console.log("Hoihoi")
    b = "0" + b;
  } else if(c.length===1){
    c = "0" + c;
  }

  return a+"-"+b+"-"+c;
}

When checkAttr() is called, the temporary argument is a="2017", b="1", c="2" for example today.
Before entering the first if, each type is: b is String and b.length is Number.(c is the same)
Therefore, the left side of the condition b.length===1 of the first if statement is true, and of course c.length===1 is also true.

The logical product is true&true and returns true, so I expected Hoi to appear on the console, but when I checked with chrome and Node, the first conditional expression was false, and the process moved to the second branch and Hoi was displayed.
Why did the first logical product become false?

javascript jquery

2022-09-30 21:21

2 Answers

It's a simple typo.

b.lengtht===1


2022-09-30 21:21

As pointed out, typo, but another approach is

 function zeroPadding(n){
    // If you add 100 digits, you always get 3 digits, so you skip the first character after stringing.
    return (100+n+"").substring(1);
}

function checkAttr(a,b,c){
    return a+"-"+zeroPadding(b)+"-"+zeroPadding(c);
}


2022-09-30 21:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.