尝试重新创建我的console.log对象

时间:2017-02-19 10:04:17

标签: javascript arrays object typescript

我有一个包含4个对象的var,当我在控制台中将其注销时,我会看到这些对象。但我一直在尝试创建这个返回变量的结构(我想对它进行排序,但首先要重新创建结构),但是在最后一个障碍中失败了。

这是控制台在原始变量上发布的内容:[Object, Object, Object, Object]

这是我使用创建的变量获得的结果:[Object]

以下是我尝试重新创建它的代码:

this.obj =      [{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                             {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                     color:'blue'}],
                    [{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                             {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                     color:'green'}],
                    [{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                             {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                     color:'red'}],
                    [{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                             {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                     color:'yellow'}]
                    ;

原始创建的的第一个对象是相同的,但为什么它看不到我的其他三个对象?如果我在代码周围添加两个[],它会看到所有四个,但后来他们已经更改为数组而不是对象......

2 个答案:

答案 0 :(得分:1)

您的代码似乎已损坏,如果您以可读的方式订购,那么它很清楚:

var obj = [
    {
        items: [{
            code: 'bravo', color: 'blue', date: '2017-01-01', pos: 'up'
        }, {
            code: 'alpha', color: 'blue', date: '2017-01-02', pos: 'down'
        }],
        color: 'blue'
    }] // <=== the array ends here, but now you have this:
    , [{ items: [{ ...

编译器然后执行此操作:

var obj = [
    {
        items: [{
                code: 'bravo', color: 'blue', date: '2017-01-01', pos: 'up'
            }, {
                code: 'alpha', color: 'blue', date: '2017-01-02', pos: 'down'
            }],
        color: 'blue'
    }
], _a = (void 0)[0], _b = ....

如您所见,它会创建另一个变量(_a)来存储其他数据。

答案 1 :(得分:1)

让任何想知道的人都能工作:

this.obj =      [{0:{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                         {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                 color:'blue'}},
                {1:{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                         {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                 color:'green'}},
                {2:{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                         {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                 color:'red'}},
                {3:{items:[{code:'bravo',color:'blue',date:'2017-01-01',pos:'up'},
                         {code:'alpha',color:'blue',date:'2017-01-02',pos:'down'}],
                 color:'yellow'}}]
                ;
}