[英]Creating a new 2D array from regular array
If I have an JavaScript array: 如果我有一个JavaScript数组:
a = ["12", "34", "56", "78"];
and I want to make a new 2D array like this: 我想制作一个新的2D数组,如下所示:
b = [ ["12345678"], ["34567812"], ["56781234"], ["78123456"] ];
I know this should be pretty simple but I just can't figure it out... My brain is kinda slow today... :/ 我知道这应该很简单,但我只是想不通...今天我的大脑有点慢...:/
Join the string at various pivot locations. 在不同的枢轴位置连接字符串。
n = [];
for(i = 0; i < a.length; i++){
n.push(a.slice(i).join("") + a.slice(0,i).join(""));
}
This outputs: 输出:
[ "12345678", "34567812", "56781234", "78123456" ]
I am not certain whether having nested single element arrays in the output was a mistake, but if that is required just add square brackets inside push
. 我不确定在输出中嵌套单个元素数组是否是一个错误,但是如果需要,只需在
push
添加方括号即可。
You can use map
in conjunction with concat
like this: 您可以将
map
与concat
结合使用,如下所示:
var newA = a.map(function() {
var copy = a.slice();
return [copy.concat(copy.splice(0, arguments[1])).join('')];
});
// => [ ["12345678"], ["34567812"], ["56781234"], ["78123456"] ];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.