Javascript:移动数组中的元素

时间:2016-11-17 13:50:42

标签: javascript

var array = ["object1","object2","object3","object4","object5"];
var copy = array.slice();
copy.forEach(function(value) {
 if(value === "object3"){
  value = "newObject3"

 }
});

console.log(copy );

如果我想将数组中的object3移动到第一个索引,我为其分配了一个新值。我该怎么做?什么是最有效,更少的时间?可以使用任何像lodash这样的库。

1 个答案:

答案 0 :(得分:1)



var array = ["object1", "object2", "object3", "object4", "object5"];
var copy = array.slice();
copy.forEach(function(value, index, theArray) {
  if (value === "object3") {
    theArray[index] = theArray[0];
    theArray[0] = "newObject3";
  }
});

console.log(copy);