没有现有的 Array 方法可以执行您想要的操作,但可以使用Array.prototype.slice
and轻松定义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);
};
然后你可以使用lcycle
andrcycle
作为普通的数组方法:
>>> 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_m
andrcycle_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" ]