gpt4 book ai didi

Javascript:移动数组中的元素

转载 作者:行者123 更新时间:2023-12-03 05:37:48 25 4
gpt4 key购买 nike

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 这样的任何库。

最佳答案

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

关于Javascript:移动数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40656677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com