如何使用循环检测数组中的空格?以及移除字符串元音时返回undefined的问题排查
Fixing Your Vowel Removal Code & Detecting Spaces
Hey there! Let's work through your code issues and answer your space-detection question, step by step.
First, let's fix that undefined issue in your vowel removal code
Your approach is totally on the right track, but two small mistakes are causing the unexpected undefined output:
- Typo in
length: You wrotearray.lenghtinstead ofarray.length— that's a super common typo! This broke your loop's boundary check. - Incorrect loop condition: Using
i <= array.lengthmakes your loop run one extra time. Wheniequals the string's length,array[i]isundefined(since indexes start at 0), and thatundefinedgets added to yournewarray.
We can also simplify your vowel check using the includes() method on your varray instead of writing all those OR conditions. Here's the fixed, cleaner code:
const originalString = "Your website is good"; const vowels = ['a', 'e', 'i', 'o', 'u']; let result = ""; for (let i = 0; i < originalString.length; i++) { const currentChar = originalString[i].toLowerCase(); if (!vowels.includes(currentChar)) { result += originalString[i]; } } console.log(result); // Output: "Yr wbst s gd"
How to detect spaces using loops
If you want to check for spaces in your string (or an array of characters), here are a few straightforward ways with loops:
Check if a space exists at all:
let hasSpace = false; for (let i = 0; i < originalString.length; i++) { if (originalString[i] === ' ') { hasSpace = true; break; // Stop checking once we find the first space } } console.log(hasSpace); // Output: true for your original stringCount how many spaces are present:
let spaceCount = 0; for (let i = 0; i < originalString.length; i++) { if (originalString[i] === ' ') { spaceCount++; } } console.log(spaceCount); // Output: 3 for your original stringIf working with an array of characters:
const charArray = originalString.split(''); let hasSpaceInArray = false; for (const char of charArray) { if (char === ' ') { hasSpaceInArray = true; break; } }
内容的提问来源于stack exchange,提问作者Mr.NewbieGoodie
相关产品推荐
相关产品推荐

