繁体   English   中英

如何从Javascript中的数组中提取多个元素?

[英]How to pull multiple elements from an array in Javascript?

因此,我正在开展一个学校项目来创建一个“钢琴”,该项目将播放在特定时间开始的音符并返回如下所示的输出:

    Outputs:
    Play A
    Play B
    Wait 1.5 seconds
    Play C
    Wait 1.5 seconds
    Release A
    Release B
    Release C

等等等等。 我能够对开始时间进行排序,但我不知道如何编写一些可以转换为我需要的输出的东西。 当格式为 note:"A" 时,我不确定如何拉出笔记。 我希望能写出一些东西,把从 0、1、2 等开始的音符按顺序拉出来,告诉他们演奏一定的时间然后释放。 我真的不知道还能怎么问这个。

    let piano=[
      {note: 'Ab', starts_at: 0},
      {note: 'A', starts_at: 5},
      {note: 'A#', starts_at: 10},
      {note: 'Bb', starts_at: 7},
      {note: 'B', starts_at: 4},
      {note: 'C', starts_at: 8},
      {note: 'C#', starts_at: 13},
      {note: 'Db', starts_at: 2},
      {note: 'D', starts_at: 0},
      {note: 'D#', starts_at: 5},
      {note: 'Eb', starts_at: 1},
      {note: 'E', starts_at: 11},
      {note: 'F', starts_at: 3},
      {note: 'F#', starts_at: 2},
      {note: 'Gb', starts_at: 9},
      {note: 'G', starts_at: 10},
      {note: 'G#', starts_at: 1}
    ];


    let my_song=piano.sort((elem_1, elem_2,) =>{
      if (elem_1.starts_at == elem_2.starts_at){
        return 0;
      } else if (elem_1.starts_at >= elem_2.starts_at){
        return 1;
      }
     return -1;
    });
    console.log(my_song)

我认为您可以在对数组进行排序以构建字符串值后放置一个 reduce。

const str = piano.reduce((acc, curr, i, arr)=>{
  const prev = arr[i - 1];
  if(prev) {
    const diff = curr.starts_at - prev.starts_at;
    acc += `\nWait ${diff} seconds`;
  }
  acc += `\nPlay ${curr.note}`;
}, '');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM