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

按指定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

  1. Unintended modification of the original word array: The line a += splitedText[i] += " "; modifies the elements in splitedText by appending a space to each word. This corrupts the original array and leads to incorrect string concatenation later in the loop.
  2. 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 exactly n groups. 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

  1. Split and count: First, we split the input string into an array of words and count the total number of words.
  2. Calculate group sizes:
    • baseWordsPerGroup is the minimum number of words each group will have (found by dividing total words by n and flooring the result).
    • groupsWithExtraWord is the remainder of that division—these are the first remainder groups that will get one extra word to ensure we use all words and end up with exactly n groups.
  3. Build groups: Loop n times, 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 with currentIndex to 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:02:35