如何在不冗余代码的前提下为密码强度检测程序添加等级描述?
First, let's fix a critical issue in your original code: the passwordStrength variable is declared globally, which means its value will persist and accumulate across multiple calls to checkPassword(). We'll move that variable inside the function to reset it each time we validate a new password.
To add the descriptive labels without making the code verbose, we can use a mapping object that directly associates strength percentages with their corresponding descriptions. This approach is clean, easy to read, and simple to modify if you ever need to adjust the labels later.
Here's the updated code:
function checkPassword(password) { // Validate input type first if (typeof password !== 'string' || password.trim() === '') { return 'Only strings are allowed'; } const trimmedPassword = password.trim(); // Check length first to skip unnecessary regex checks if invalid if (trimmedPassword.length < 6 || trimmedPassword.length > 12) { return 'Password can not be less than 6 or greater than 12 characters'; } // Initialize strength inside the function to avoid cross-call accumulation let passwordStrength = 0; const validationRules = [ /[a-z]/, // Lowercase letters /[A-Z]/, // Uppercase letters /[0-9]/, // Numbers /[$@#&!]/ // Special characters ]; // Check each rule and increment strength validationRules.forEach(rule => { if (rule.test(trimmedPassword)) { passwordStrength += 25; } }); // Map strength percentage to descriptive label const strengthLabels = { 25: 'poor', 50: 'weak', 75: 'medium', 100: 'strong' }; // Return the matching label return strengthLabels[passwordStrength]; } console.log(checkPassword('@manGaLa')); // Returns 'medium'
Key Improvements:
- Fixed global variable issue:
passwordStrengthnow lives inside the function, so it resets to 0 for every new password check. - Early length validation: We check password length first to avoid wasting time on regex tests if the length is already invalid.
- Cleaner rule management: Using an array for validation regexes makes it easy to add/remove rules later without rewriting repetitive
ifstatements. - Concise label mapping: The
strengthLabelsobject eliminates messy nestedif/elsechains, making the code more maintainable.
If you want to return both the percentage and description (e.g., "75% (medium)"), just adjust the return line to:
return `${passwordStrength}% (${strengthLabels[passwordStrength]})`;
内容的提问来源于stack exchange,提问作者danoseun

