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

React中如何将API接口返回的数据转为数组并实现单词字母打乱功能

实现方案

你已经成功获取到接口返回的句子文本,后续处理逻辑直接按下方步骤实现即可:

  • 用split(' ')方法将完整句子按空格切割,直接得到单词数组
  • 写单独的单词打乱工具函数:仅长度大于3的单词需要处理,保留首字母和尾字母,用洗牌算法打乱中间部分字符后重新拼接
  • 遍历单词数组对每个单词调用打乱函数,可根据需求保留数组格式或拼接为打乱后的完整句子
import React from 'react';
import './App.css';

// 单词打乱工具函数
const shuffleWord = (word) => {
  if (word.length <= 3) return word;
  const firstChar = word[0];
  const lastChar = word[word.length - 1];
  let middleChars = word.slice(1, -1).split('');
  // 洗牌算法打乱中间字符
  for (let i = middleChars.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [middleChars[i], middleChars[j]] = [middleChars[j], middleChars[i]];
  }
  return firstChar + middleChars.join('') + lastChar;
}

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      originWordArr: [],
      shuffledWordArr: [],
      shuffledSentence: ''
    };
  }

  componentDidMount() {
    let url = 'https://api.hatchways.io/assessment/sentences/1';
    fetch(url, {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    }).then((result) => result.json())
      .then((resp) => {
        const originSentence = resp.data.sentence;
        // 转换为单词数组
        const wordArr = originSentence.split(' ');
        // 生成打乱后的单词数组和句子
        const shuffledArr = wordArr.map(shuffleWord);
        const shuffledStr = shuffledArr.join(' ');
        this.setState({
          originWordArr: wordArr,
          shuffledWordArr: shuffledArr,
          shuffledSentence: shuffledStr
        })
      })
  }

  render() {
    const { shuffledSentence, shuffledWordArr } = this.state;
    return (
      <div>
        {
          shuffledSentence ?
            <div>
              <h1 className="title">{shuffledSentence}</h1>
              <p>打乱后的单词数组:{JSON.stringify(shuffledWordArr)}</p>
              {/* 原有注释的业务逻辑可直接在这里补充 */}
            </div>
            : <h1>Please wait...</h1>
        }
      </div>
  )}
  
}

export default App;

如果需要使用原始单词数组,直接调用state中存储的originWordArr即可。

内容的提问来源于stack exchange,提问作者tabanoa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:48:04