在每个nt-h数组元素之后插入新元素 [英] Insert new element after each nt-h array elements
问题描述
我有一个名为a
的数组,我想在数组a
的每个nt-h
元素之后插入一个元素.例如,我想将字符串XXX
放在数组a
的每个3
元素之后,结果得到一个新的数组b
,如下面的示例所示:
let a = [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ];
let b = [undefined, "", 0, "XXX", [], "ee", false, "XXX", null, {}, Date(), "XXX", true, (z)=>2*z, [], "XXX", NaN];
console.log(a, b);
我试图通过这种方式做到这一点:
b = [];
a.map((x, i) => b.push((i + 1) % 3 ? x : "XXX"));
https://jsfiddle.net/Lamik/vjfaqn3u/16/ >
但是,有一个问题:输出b
数组的长度与输入a
的长度相同,这是错误的.有什么想法或替代解决方案吗?
(更新:就地解决方案也可以;我剪切了数组a
)
let a= [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ];
let n = 3+1;
let currentPosition = 3;
let temp ='xxxxxx';
console.log('Before assignment:::',a.length, a);
while(currentPosition <= (a.length+1)){
a.splice(currentPosition,0,temp);
currentPosition += n;
}
console.log('new array length:::::',a.length ,a);
我希望这个解决方案对您来说很好. 在插入元素之前,长度为13.在17.之后.
I have an array called a
and I want to insert an element after every nt-h
elements of the array a
. For example, I want to put the string XXX
after each 3
elements of the array a
and as result get a new array b
as shown on the next example:
let a = [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ];
let b = [undefined, "", 0, "XXX", [], "ee", false, "XXX", null, {}, Date(), "XXX", true, (z)=>2*z, [], "XXX", NaN];
console.log(a, b);
I have tried to do it in this way:
b = [];
a.map((x, i) => b.push((i + 1) % 3 ? x : "XXX"));
https://jsfiddle.net/Lamik/vjfaqn3u/16/
However, there is a problem: The output b
array has the same length as input a
which is wrong. Any idea or alternative solution?
(UPDATE: in-place solutions are also ok; I cut array a
)
let a= [undefined, "", 0, [], "ee", false, null, {}, Date(), true, (z)=>2*z, Array(0), NaN ];
let n = 3+1;
let currentPosition = 3;
let temp ='xxxxxx';
console.log('Before assignment:::',a.length, a);
while(currentPosition <= (a.length+1)){
a.splice(currentPosition,0,temp);
currentPosition += n;
}
console.log('new array length:::::',a.length ,a);
I hope this solution will be fine for you. Before inserting the element a length is 13. After 17.
这篇关于在每个nt-h数组元素之后插入新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!