简体   繁体   English

使用Javascript / Typescript从1D数组创建3D数组

[英]Create 3D array from 1D array in Javascript/Typescript

I would like to create 3D array of 1D I have 我想创建1D的3D数组

  let a = ['hello', 'my', 'friend']

And I tried to create 3D array like this 我试图像这样创建3D数组

b = [[['h'], ['e'], ['l'], ['l'], ['o']], [['m'], ['y']], [['f'], ['r'], ['i'] ,['e'], ['n'], ['d']]]

but nothing works.. 但没有任何效果..

How could I do something like this? 我该怎么做?

This uses the spread operator to implicitly invoke String#[@@iterator]() for each word and then map() s each character to a unit-length array: 这使用散布运算符为每个单词隐式调用String#[@@iterator]() ,然后map()每个字符map()为单位长度的数组:

 let a = ['hello', 'my', 'friend']; let b = a.map(word => [...word].map(c => [c])); console.log(JSON.stringify(b)); 

If you are attempting to run this using Typescript as a preprocessor, you'll need to call the generically implemented Array#slice() on each word instead, since they are Array-like objects (and for some reason Typescript doesn't recognize that): 如果您尝试使用Typescript作为预处理器来运行此程序,则需要对每个单词调用通用实现的Array#slice() ,因为它们是类似Array的对象(由于某种原因,Typescript无法识别):

 let slice = Function.call.bind(Array.prototype.slice); let a = ['hello', 'my', 'friend']; let b = a.map(word => slice(word).map(c => [c])); console.log(JSON.stringify(b)); 

Using map twice works just fine. 两次使用地图都可以。

let a = ['hello', 'my', 'friend'];

let result = a.map((word) => word.split('')
.map((letter) => [letter]))

console.log(result)

here is a more rudimentary option 这是一个更基本的选择

function convertStringIntoArray(str){
    var arr = [];
    var words = str.split(" ");
    for(var j=0; j<words.length; j++){
        var word = words[j];
        var innerArr = [];
        for(var i=0; i<word.length; i++){
            innerArr.push([word.charAt(i)]);
        }
        arr.push(innerArr);
    }
    return arr;
} 

The map command returns an array - so by calling it once you will get an array characters. map命令返回一个数组-因此,一旦调用它,您将获得一个数组字符。

a.map(function(item) { return [ item.split('') ]; })
// [[["h","e","l","l","o"]],[["m","y"]],[["f","r","i","e","n","d"]]]

If you call map a second time for each character, you can wrap each item in an array. 如果您第二次为每个字符调用map,则可以将每个项目包装在数组中。

let b = a.map(function(item) { 
    return item.split('').map(function(inner) { 
                                    return [ inner ]; 
                                }); 
})
// [[["h"],["e"],["l"],["l"],["o"]]],[[["m"],["y"]]],[[["f"],["r"],["i"],["e"],["n"],["d"]]]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM