课程: JavaScript Practice: String Manipulation

Solution: Determine password length - JavaScript教程

课程: JavaScript Practice: String Manipulation

Solution: Determine password length

- [Instructor] In this challenge, our goal was to find the length of the password provided in the variable password. This type of problem is a common one you may run into when working with JavaScript, especially if you're working with forms and validations. If we look at the result variable in the test code, we see that it is set equal to the findPasswordLength function on Line 13, and the variable password is passed in as an argument. The first step here is to determine the length of the password. The string object has a built-in property called length that will return the length of a string as a number. For this challenge, we need to determine the length of the string and then return a message depending on the length. First, let's start by logging out the length of the password so you can see the value return. On Line 15, I'm just going to console.log password, and then we're going to apply the property length. Let's run that and see what that returns for us. All right, so 20. So our password length we know is 20. The instructions indicate that we should return the message success, which is on Line 10, tied to the variable success if the password is greater than or equal to eight in length. If the password is less than eight characters, we should return the message, password should be at least eight characters, and that's tied to the needLongerPassword variable on Line 11. So to get to the solution, we need to write a statement that evaluates the password length. Let's go ahead and get rid of this console.log, and let's start with our return. And we're going to return password.length 'cause we know we need to get that to determine what message to send. And we know that we want to return success if the password length is greater than or equal to eight. Now we're going to use a ternary which evaluates the left-hand side of this question mark. If it evaluates to truth, truthy or true, then we're going to return success. Then on the right side of the colon, if it evaluates to false or falsy, we're going to return the needLongerPassword variable. All right, let's go ahead and run it and let's see what our solution is. Awesome, you did it. It's exactly right. Just as it says there, success. Great work.

内容