You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用循环检测数组中的空格?以及移除字符串元音时返回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:

  1. Typo in length: You wrote array.lenght instead of array.length — that's a super common typo! This broke your loop's boundary check.
  2. Incorrect loop condition: Using i <= array.length makes your loop run one extra time. When i equals the string's length, array[i] is undefined (since indexes start at 0), and that undefined gets added to your newarray.

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 string
    
  • Count 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 string
    
  • If 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 07:12:29