【问题标题】:How do I iterate through an object using .map? [duplicate]如何使用 .map 遍历对象? [复制]
【发布时间】:2020-02-17 03:05:46
【问题描述】:

我有一个应用程序,它根据您按下的按钮从所选数组中播放随机声音。我还想提供按需列出数组中所有声音的选项。

我一直在考虑使用 for 循环和 .map 的各种不同的建议,但我总是碰壁,因为我不能在对象上使用 .map ......我想。

class Randomizer extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      currentSound: {name: "laser", sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Collision8-Bit.ogg"},
        myArray: [
          {
            name: 'laser',
            sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Collision8-Bit.ogg"
          },
          {
            name: 'laugh',
            sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Evillaugh.ogg"
          },
          {
            name: 'jump',
            sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/jump.ogg"
          }
        ],
        myArraySequel: [
          {
            name: 'laser2',
            sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Collision8-Bit.ogg"
          },
          {
            name: 'laugh2',
            sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Evillaugh.ogg"
          },
          {
            name: 'jump2',
            sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/jump.ogg"
          }
        ]
        }
  }

  newSound(arr){
    this.setState((prevState)=>{
      return {currentSound: prevState[arr][Math.floor(Math.random()*prevState[arr].length)]}
    })
  };



  render() {
    return (
      <div>
        <button onClick={()=>{this.newSound('myArray')}}>Sounds from myArray</button>
        <button onClick={()=>{this.newSound('myArraySequel')}}>myArraySequel</button>
        <div>
            Listen! 
            <audio
              autoPlay
              src={this.state.currentSound.sound}>            
            </audio>
            <h2>{this.state.currentSound.name}</h2>           
        </div>
        <div>
          <h2>sounds from myArray</h2>
          {/* list of buttons with the name value as the the button name and it will play the sound associated when pressed */}
        </div>
      </div>
    );
  }
}

function App() {
  return (
    <div className="App">
     <h1>RandomSoundboard</h1>
     <Randomizer />
    </div>
  );
}

export default App;

当我使用 .map 时,它会告诉我当然要使用数组。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您可以轻松做到这一点,

    语法是这样的,

    array.map((element,index)=>(
      <button>{element.name}</button>
    ))
    

    你的代码会是这样的

    {
      this.state.myArray.map((element,index)=>(
          <button>{element.name}</button>
      ))
    }
    

    【讨论】:

    • @JoshWren 欢迎您,您可以接受我的回答(如果对您有帮助)以供将来使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2019-01-03
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多