Javascript 循环行为

标签 javascript arrays loops theory

alltones 数组包含音阶中所有可能的音符。

var alltones = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ];

我想获取用户输入的一个音调,然后构建一个包含数组某些元素的列表。

假设我从 alltones[5]"F" 开始,并希望从该点开始获取数组的第二个元素并将其放入我的列表中,直到我回到 "F"。该数组更像是一个圆而不是直线列表。我有点不确定一旦循环到达最后一个元素,数组将如何运行。

我是否通过根据用户输入生成一个新数组来解决问题。或者有没有一种方法让 JavaScript 知道在数组到达末尾时循环回到数组的开头,从而将数组视为一个圆圈?

一个例子: 用户输入 = F
我正在寻找的输出是从 F 开始计数(每两个项目),直到我们回到数组到 F
所以所需的输出将是 => F G A B C# D#

最佳答案

没有 existing Array method做你想做的事,但使用 Array.prototype.slice 很容易定义一个和 Array.prototype.concat :

// move i elements from the start of the array to the end of the array
Array.prototype.lcycle = function(i) {
  var xs = this.slice(0,i);
  var ys = this.slice(i);
  return ys.concat(xs)
};
// move i elements from the end of the array to the start of the array
Array.prototype.rcycle = function(i) {
  var xs = this.slice(0,-i);
  var ys = this.slice(-i);
  return ys.concat(xs);
};

然后你可以像普通数组方法一样使用lcyclercycle:

>>> alltones.lcycle(3)
[ "D#" , "E" , "F" , "F#" , "G" , "G#" , "A" , "A#" , "B" , "C" , "C#" , "D" ]
>>> alltones.rcycle(4)
[ "G#" , "A" , "A#" , "B" , "C" , "C#" , "D" , "D#" , "E" , "F" , "F#" , "G" ]

请注意,这两种方法都返回一个新数组。如果你想改变原始数组,你可以使用 Array.prototype.splice 定义类似的方法。 .

// move i elements from the start of the array to the end of the array, mutating the original array
Array.prototype.lcycle_m = function(i) {
  var args = this.splice(0,i);
  args.unshift(0);
  args.unshift(this.length);
  this.splice.apply(this, args);
};
// move i elements from the end of the array to the start of the array, mutating the original array
Array.prototype.rcycle_m = function(i) {
  var args = this.splice(-i);
  args.unshift(0);
  args.unshift(0);
  this.splice.apply(this, args);
};

同样,您可以将 lcycle_mrcycle_m 用作普通数组方法:

>>> alltones.lcycle_m(3)
>>> alltones
[ "D#" , "E" , "F" , "F#" , "G" , "G#" , "A" , "A#" , "B" , "C" , "C#" , "D" ]
>>> alltones.rcycle_m(3)
>>> alltones
[ "C" , "C#" , "D" , "D#" , "E" , "F" , "F#" , "G" , "G#" , "A" , "A#" , "B" ]

关于Javascript 循环行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14789157/

相关文章:

javascript - 使用 JavaScript 和 AJAX 从 HTML 输入标记检索图像并将其传递给 PHP 脚本以上传到数据库

arrays - 在二维数组中搜索元素

c# - LINQ:如何跳过一个然后获取序列的其余部分

javascript - 如何迭代彼此独立的列表组

javascript - JS中的Bigint破坏了数组排序?

JavaScript 对象构造

C:是否可以合并/分组字符数组中的某些元素,使其成为字符串数组?

c# - 如何在不在代码中自己指定数组长度的情况下用用户输入填充数组

javascript - 如何阻止激烈的 Javascript 循环卡住浏览器

javascript - 如何确保一个对象数组只包含一个带有 Joi 的特定键?