简体   繁体   中英

understanding this javascript function code

function isBlank(s){
    var len = s.length
    var i
    for(i=0; i<len; ++i) {
        if(s.charAt(i)!= " ") return false
    }
    return true
}

I am totally new to JavaScript and coding. Please can someone explain me how is this code working. I know that it is being used to check whether a input box has some value or not, but I know no further.

question update.... See, in the above code, the for loop runs and if the string is not blank it returns false. Now for loop ends and browser reads the next line which is-- returns true--. So is not the function finally returning true. No matter if there was a return false in the middle.

It is looping through the string s and checking if each character is a space. If there are characters other than spaces, then the function returns false, because the string is not blank. If the string is empty or only contains spaces, then it returns true because the string is blank.

function isBlank(s){ // it is a function named 'isBlank' that accept one parameter, that the parameter is something passed from the outside
    var len = s.length // Assign the length of parameter 's' into a local variable 'len'
    var i // Declare a new local variable 'i'
    for(i=0;i<len;++i) { // This is a 'loop', you can google it
        if(s.charAt(i)!= " ") return false // if any character inside the parameter 's' is not an empty space, that means it isn't blank, so return false
    }
    return true; // If code reach this line that means 's' is either with 0 length or all characters of it are an empty space
}

By using the above function:

alert(isBlank("123")); // false

alert(isBlank("")); // true

alert(isBlank(" ")); //true

The function checks whether the string is empty or not.

for(i=0;i<len;++i) { // iterates through the string
    if(s.charAt(i)!= " ") // checks whether character at index i of string s is not equal to " ".
        return false 
}

It iterates through the string and returns false if any character is not equal to " ".s.charAt(i) returns the character at index i of the string s. If the condition is not satisfied for every character then it returns true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM