如何在给定特定元素索引的情况下替换数组中的元素?

时间:2019-01-30 16:22:34

标签: javascript arrays

var array = ['odd', 'odd', 2, 8, 'odd', 4];
var oddArr = [1, 3, 5];

如何用oddArr中的元素替换数组中的“ odd”,从而使

var newArr = [1, 3, 2, 8, 5, 4];

6 个答案:

答案 0 :(得分:5)

遍历数组,如果发现ModifyUser,则使用odd将其替换为oddArr中的元素

array.shift()

答案 1 :(得分:3)

您可以使用map和这样的索引变量:

var array = ["odd", "odd", 2, 8, "odd", 4];
var oddArr = [1, 3, 5];

let currentIndex = 0;
const newArray = array.map(a => a === 'odd' ? oddArr[currentIndex++] : a)

console.log(newArray)

答案 2 :(得分:1)

您可以接管索引的封闭,没有突变oddArr

const
    array = ['odd', 'odd', 2, 8, 'odd', 4],
    oddArr = [1, 3, 5],
    result = array.map((i => v => v === 'odd' ? oddArr[i++] : v)(0));

console.log(result);

答案 3 :(得分:0)

您可以通过一个简单的循环来做到这一点:

var array = ["odd", "odd", 2, 8, "odd", 4];
var oddArr = [1, 3, 5];

var result = [], i = 0;
array.forEach(function(x) {
  if (x === "odd") {
    result.push(oddArr[i]);
    i++;
  }
  else {
    result.push(x);
  }
});

console.log(result);

(请注意,我已经将odd替换为字符串"odd",如果odd是一个实变量,则可以在上面的代码中使用它。)

答案 4 :(得分:0)

奇数应包装在''中。

var array = ['odd', 'odd', 2, 8, 'odd', 4];
var oddArr = [1, 3, 5];
//lopping through array
for(let i = 0;i<array.length;i++){
    //check if item at i is odd
	if(array[i] === 'odd'){
        //oddArr.shift() returns the first element and also removes it.
		array[i] = oddArr.shift();
	}
}
console.log(array);

答案 5 :(得分:0)

循环通过用foreach(阵列)和从oddArr改变与横积水一个奇数值,并创建索引计数器(x)的像以下

var array = ["odd","odd", 2, 8, "odd", 4];
var oddArr = [1, 3, 5];
var x=0;
array.forEach(function(v,i){
 if(array[i]=="odd")
 {array[i]=oddArr[x]; x++;}
 });
 console.log(array);