简体   繁体   English

javascript 用第二个数组值替换第一个数组值。 第一个数组长度为 2,第二个数组长度为 7

[英]javascript replace first array value with second array value. First array length is 2 and second one length is 7

I have two arrays a and b and i need to replace array b value with a.我有两个数组 a 和 b,我需要用 a 替换数组 b 的值。

a= [1,2];
b=[1,2,3,4,5,6,7];

Expected output should be like this预期的输出应该是这样的

[1,2,1,2,1,2,1]

Simply简单地

var output = b.map( function(item, index){
  return a[ index % a.length ]
});

Demo演示

 var a= [1,2]; var b=[1,2,3,4,5,6,7]; var output = b.map( function(item, index){ return a[ index % a.length ] }); console.log( JSON.stringify( output ) )

You could take the index of the target array and map the value of source array with the index and remainder operator for the given length.您可以获取目标数组的索引,并使用给定长度的索引和余数运算符映射源数组的值。

 var a = [1, 2], b = [1, 2, 3, 4, 5, 6, 7]; b = b.map((_, i) => a[i % a.length]); console.log(b);

You can use forEach to change the array in place and modulo to get the right index.您可以使用 forEach 就地更改数组并取模以获得正确的索引。 You also can use map on the array if you want a new one.如果你想要一个新的,你也可以在数组上使用 map。

 var a = [1,2] var b = [1,2,3,4,5,6,7] var l = a.length b.forEach((el,idx,arr) => { arr[idx] = a[idx%l] }) console.log(b)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将第二个数组对象值添加到 javascript 中的第一个对象数组中 - Unable to add second array object value into first array of objects in javascript 为什么返回-1在javascript中排序第二个数组之前的第二个值 - why does return -1 sort the first value of an array before the second in javascript 相对于 javascript 中的第一个数组对第二个数组进行排序 - Sorting second array with respect to first array in javascript 从第二个数组中存在的第一个数组中删除值 - Remove value from first array that exists in the second array 通过比较字段更新基于第二个数组的第一个数组对象值 - Update the first array object value based on the second array by comparing a field 如何通过第一个数组的输入返回第二个数组的值 - How to return the value of the second array through the input of the first array 如何将第一个数组中索引[0]的值赋给第二个数组中的索引[0]? - How to assign a value from index[0] in first array to index[0] in second array? 用第二个数组中的匹配属性替换一个数组中的值 - Replace value in one array with matching properties from second array 基于第一个值作为键和第二个值作为javascript中的值创建一个对象数组 - Create an array of object based on first value as key and second value as value in javascript 用一个值替换第一次出现,用另一个值替换第二次 - Replace first occurrence with one value and second with another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM