如何在Javascript中将项目数组向上移动4个位置?
我有以下字符串数组:
var array1 = ["t0","t1","t2","t3","t4","t5"];
我需要一个函数转换"array1"导致:
// Note how "t0" moves to the fourth position for example var array2 = ["t3","t4","t5","t0","t1","t2"];
提前致谢.
array1 = array1.concat(array1.splice(0,3));
在Firebug中运行以下内容进行验证
var array1 = ["t0","t1","t2","t3","t4","t5"]; console.log(array1); array1 = array1.concat(array1.splice(0,3)); console.log(array1);
结果是
["t0", "t1", "t2", "t3", "t4", "t5"] ["t3", "t4", "t5", "t0", "t1", "t2"]
您可以对数组进行切片,然后以相反的顺序连接它:
var array2 = array1.slice(3).concat(array1.slice(0, 3));