【问题标题】:Transform Array from one row Array to multiple row array将数组从单行数组转换为多行数组
【发布时间】:2016-03-04 11:19:19
【问题描述】:

我有一个返回如下值的数组:

0: 1,2,3,4

我需要它返回这样的数组值:

0: 1
1: 2
2: 3
3: 4

如果我用javascript来做,我该怎么做?

【问题讨论】:

  • 输入是array([1,2,3,4]) 或object({0:[1,2,3,4]}) ?

标签: javascript arrays transform


【解决方案1】:

带有循环,例如。

var object = { '0': [1, 2, 3, 4] },       // the object
    result = function (o) {               // the iife for the result
        var r = {};                       // the temporary variable
        o['0'].forEach(function (a, i) {  // the loop over the property zero
            r[i] = a;                     // the assignment to the object with
        });                               // the wanted key
        return r;                         // the return of the temporary object
    }(object);                            // the start with the object

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

【讨论】:

    【解决方案2】:

    你可以这样做:

    var array = ['1,2,3,4'];
    console.log(array[0].split(','));

    【讨论】:

    • 我得到这个错误:Uncaught TypeError: sortOrderValues[0].split is not a function
    • 你能不能做console.log(sortOrderValues)给我输出,谢谢
    【解决方案3】:
    i have an array that returns the values like this:
    
    0: 1,2,3,4
    

    试试这个

    "0: 1,2,3,4".split(":").pop().split(",").map( function(value){return [value]} );
    

    【讨论】:

    • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
    • @DanielCheung 立即查看
    猜你喜欢
    • 1970-01-01
    • 2020-05-10
    • 2016-11-28
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2015-12-24
    相关资源
    最近更新 更多