按指定n值分割空格字符串:JavaScript代码输出异常求修正
Fixing the String Splitting Function to Divide into Exactly n Elements
Let's fix this string splitting function so it correctly divides the input into exactly n elements as expected. First, let's break down what was wrong with the original code, then walk through the corrected version.
Issues with the Original Code
- Unintended modification of the original word array: The line
a += splitedText[i] += " ";modifies the elements insplitedTextby appending a space to each word. This corrupts the original array and leads to incorrect string concatenation later in the loop. - Incorrect grouping logic: The original code uses
Math.ceil(splitedText.length / number)to determine when to finalize a group, which doesn't guarantee we end up with exactlyngroups. For example, in your first test case, this logic results in only 2 groups instead of the expected 3.
Corrected Code
Here's a revised function that follows your expected behavior:
function getSplitedText(number, word) { const splitedText = word.split(" "); const totalWords = splitedText.length; const result = []; let currentIndex = 0; // Calculate base number of words per group, and how many groups need an extra word const baseWordsPerGroup = Math.floor(totalWords / number); const groupsWithExtraWord = totalWords % number; for (let i = 0; i < number; i++) { // Determine how many words to include in the current group const wordCount = i < groupsWithExtraWord ? baseWordsPerGroup + 1 : baseWordsPerGroup; // Extract the slice of words and join into a string const group = splitedText.slice(currentIndex, currentIndex + wordCount).join(" "); result.push(group); // Move the index forward for the next group currentIndex += wordCount; } return result; } // Test your examples console.log(getSplitedText(3, "SIZZLING STEAK TERIYAKI BOY")); // Output: ["SIZZLING STEAK", "TERIYAKI", "BOY"] console.log(getSplitedText(2, "POWERVILLE FUN RIDES")); // Output: ["POWERVILLE FUN", "RIDES"] console.log(getSplitedText(3, "POWERVILLE FUN RIDES")); // Output: ["POWERVILLE", "FUN", "RIDES"]
How the Corrected Logic Works
- Split and count: First, we split the input string into an array of words and count the total number of words.
- Calculate group sizes:
baseWordsPerGroupis the minimum number of words each group will have (found by dividing total words bynand flooring the result).groupsWithExtraWordis the remainder of that division—these are the firstremaindergroups that will get one extra word to ensure we use all words and end up with exactlyngroups.
- Build groups: Loop
ntimes, each time extracting the correct number of words from the array, joining them into a string, and adding it to the result array. We track our position in the word array withcurrentIndexto avoid overlapping groups.
This approach ensures we always get exactly n elements, with the extra words (when total words aren't divisible by n) distributed to the earliest groups—matching your expected output perfectly.
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

