2016-11-17 94 views
0
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的庫都可以使用。Javascript:陣列中的移動元素

+0

[array.prototype.push(https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/push)是你尋求。 –

+2

這個問題在這個問題中討論得很好:http://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another –

+0

而那些不是真正的物體,但字符串? – adeneo

回答

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);