如果您处理的变量超过 2 个,最好使用数组,因为数组具有内置函数,您可以使用
var nums = [1,2,3]; // this is your array. it can have any length you want
// this is one line that does the magic
nums.push(nums.shift()); // to the left
nums.unshift(nums.pop()); // to the right
http://jsfiddle.net/wbKYY/2/
http://jsfiddle.net/wbKYY/4/
不管怎样,关于你的评论。由于您将旋转的指针不是预先确定的,并且会有所不同,因此最好使用一个函数。
将遍历您定义的指针的函数。
function rotateArr(arr,pointers,dir) {
var narr = arr; // create a local copy we can use it
var savevalue;
if (dir == 1) { // rotate to the right
savevalue = narr[pointers[pointers.length-1]]; // save the last value
for(var i=pointers.length-2;i>=0;i--) {
narr[pointers[i+1]] = narr[pointers[i]];
}
narr[pointers[0]] = savevalue; // set the first value
} else { // rotate to the left
savevalue = narr[pointers[0]]; // save the first value
for(var i=0;i<pointers.length-1;i++) {
narr[pointers[i]] = narr[pointers[i+1]];
}
narr[pointers[pointers.length-1]] = savevalue; // set the last value
}
return narr;
}
// arr is the array of faces
// pointers is the elements which you want to rotate (an array)
// dir is either 1 or -1
您可以使用执行此功能
nums = rotateArr(nums,[pointers],[1,-1]);
// just some examples
nums = rotateArr(nums,[0,1,2,5],1);
nums = rotateArr(nums,[3,6,1,4],-1);
这是一个工作示例:
http: //jsfiddle.net/w2jGr/
但是,如果您更喜欢使用只是数组方法的原型函数,您可以定义一个属性并从那里访问它。
Object.defineProperty(Object.prototype, "rotateArr", { value: function(pointers,dir) {
var savevalue;
if (dir == 1) { // rotate to the right
savevalue = this[pointers[pointers.length-1]]; // save the last value
for(var i=pointers.length-2;i>=0;i--) {
this[pointers[i+1]] = this[pointers[i]];
}
this[pointers[0]] = savevalue;
} else { // rotate to the left
savevalue = this[pointers[0]]; // save the last value
for(var i=0;i<pointers.length-1;i++) {
this[pointers[i]] = this[pointers[i+1]];
}
this[pointers[pointers.length-1]] = savevalue;
}
}, enumerable : false});
永远不建议修改对象的原型,但如果您不想要干净的代码并且想要可用性或可读性,这很有效,因为您可以调用函数
nums.rotate([pointers],dir);
http://jsfiddle.net/w2jGr/1/