Jan*_*egg 16 javascript arrays
什么是最简单的方法(使用"原生"javascript)来复制javascript数组中的每个元素?
订单很重要.
例如:
a = [2, 3, 1, 4]
// do something with a
a
// a is now [2, 2, 3, 3, 1, 1, 4, 4]
Run Code Online (Sandbox Code Playgroud)
axe*_*uch 17
我想出了类似于tymeJV的回答
[2, 3, 1, 4].reduce(function (res, current, index, array) {
return res.concat([current, current]);
}, []);
Run Code Online (Sandbox Code Playgroud)
Zey*_*man 10
基本上你可以flatMap
在 ES19 中使用
a = [1, 2, 3, 4];
a.flatMap(i => [i,i]); // [1, 1, 2, 2, 3, 3, 4, 4]
Run Code Online (Sandbox Code Playgroud)
您也可以像这样自定义重复次数:
a = [1, 2, 3, 4];
const dublicateItems = (arr, numberOfRepetitions) =>
arr.flatMap(i => Array.from({ length: numberOfRepetitions }).fill(i));
dublicateItems(a, 3);
Run Code Online (Sandbox Code Playgroud)
基本上:
a = [2, 3, 1, 4];
b=[];
for(var i = 0; i< a.length;++i){
b.push(a[i]);
b.push(a[i]);
}
a=b;
Run Code Online (Sandbox Code Playgroud)
我在我的应用程序中遇到了这个问题,所以我创建了这个函数:
function duplicateElements(array, times) {
return array.reduce((res, current) => {
return res.concat(Array(times).fill(current));
}, []);
}
Run Code Online (Sandbox Code Playgroud)
要使用它,只需传递数组以及您希望元素重复的次数:
duplicateElements([2, 3, 1, 4], 2);
// returns: [2, 2, 3, 3, 1, 1, 4, 4]
Run Code Online (Sandbox Code Playgroud)
我想你可以这样做:
var duplicated = a.map(function(item) {
return [item, item];
}).reduce(function(a, b) { return a.concat(b) });
//duplicated: [2, 2, 3, 3, 1, 1, 4, 4]
Run Code Online (Sandbox Code Playgroud)