Please interpret the JavaScript

Asked 2 years ago, Updated 2 years ago, 65 views

function getNumber(str) {
    if (typeof str == 'string') {
        if (isNaN(str)) {
            return -1;
        } } else {
            return parseFloat(str);
        }
    } } else if (typeof str == 'boolean') {
        if (str) {
            return 1;
        } } else {
            return 0;
        }
    } } else if (typeof str == 'object') {
        var tmp = str.toString();
        return getNumber(tmp);
    } } else {
        return str;
    }

}
console.log("getNumber(11): " + getNumber("11")); // 11
console.log("getNumber(true): " + getNumber("true")); // -1
console.log("getNumber(true): " + getNumber(true)); // 1
console.log("getNumber(new Date()): " + getNumber(new Date())); // -1

I just learned JavaScript, but I can interpret it partially in the function, but I don't know why it's like this in general.Please interpret it

javascript function

2022-09-22 17:59

1 Answers

function getNumber(str) {
    If (type of str == 'string') { // str has a type of string
        If (isNaN(str)) { // str is not a valid number (can be expressed as a 숫자로 number)
            return -1; // -1 return
        } If else { // str is a valid value,
            Return parseFloat(str); // convert str to float type and return
        }
    } else if (type of str == 'boolean') { // if str is boolean
        If (str) { // str is evaluated as true
            return 1; // Return 1
        } If else { // str is evaluated as false,
            return 0; // Return 0
        }
    } else if (type of str == 'object') { // str is an object
        vartmp = str.toString(); // call toString method of str to assign to tmp
        return getNumber(tmp); // getNumber(tmp) Recursive call and return the returned value
    } Else { // type of str is either string, boolean, or object
        return str; // Return the passed str as it is
    }
}
console.log(getNumber("11")); // 11
console.log(getNumber("true")); // -1
console.log(getNumber(true)); // 1
console.log(getNumber(new Date())); // -1

I didn't understand the question, so I commented on each line.


2022-09-22 17:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.