在JavaScript中删除数组的第一个元素/数组

时间:2017-09-21 10:27:18

标签: javascript arrays

我在删除数组的第一个元素时遇到问题。

简而言之,如果我在控制台中显示它,这就是我的数组的样子:

(11) [Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4)]
0 : (4) ["2017-09-20T16:00:00-07:00", 188.125, 0, 1]
1 : (4) ["2017-09-20T17:00:00-07:00", 123.125, 0, 1]
2 : (4) ["2017-09-20T18:00:00-07:00", 114.25, 0, 1]
3 : (4) ["2017-09-20T19:00:00-07:00", 115, 0, 1]
4 : (4) ["2017-09-20T20:00:00-07:00", 113.25, 0, 1]
5 : (4) ["2017-09-20T21:00:00-07:00", 115.625, 0, 1]
6 : (4) ["2017-09-20T22:00:00-07:00", 114.75, 0, 1]
7 : (4) ["2017-09-20T23:00:00-07:00", 114, 0, 1]
8 : (4) ["2017-09-21T00:00:00-07:00", 112.625, 0, 1]
9 : (4) ["2017-09-21T01:00:00-07:00", 108.375, 0, 1]
10 : (4) ["2017-09-21T02:00:00-07:00", 111.125, 0, 1]
length : 11
__proto__ : Array(0)

我想删除第一个0,我尝试使用.shift()但是没有效果。

就像我的数组名为myArray.data并尝试myArray.data.shift()一样,我收到此错误消息:

TypeError: Cannot read property '0' of undefined
    at bundle.js:1554
    at Function._.map._.collect (vendor.js:11761)
    at renderChart (bundle.js:1547)
    at bundle.js:1611
    at Scope.$digest (vendor.js:34716)
    at Scope.$apply (vendor.js:34986)
    at bundle.js:259
    at vendor.js:14387
    at _fulfilled (vendor.js:13992)
    at self.promiseDispatch.done (vendor.js:14021)

任何想法如何解决这个问题?

  

稍后编辑:

代码在图表生成函数中,这是整个片段:

data: {
    type: chartType,
    columns: [
        ['x'].concat(_.map(myArray.data, function (dataPoint) {

        const x = (myArray.data).shift();
        console.log(myArray.data);          
        console.log(x);

            return moment(dataPoint[0]).valueOf();
        })),
        ['Expected'].concat(_.map(myArray.data, function (dataPoint) {
            return dataPoint[1];
        })),
        ['Actual'].concat(_.map(myArray.data, function (dataPoint) {
            return dataPoint[1];
        }))
    ],
    x: 'x'
},

3 个答案:

答案 0 :(得分:3)

我可以使用Array.shift()

重现想要的结果



let arr = [
["2017-09-20T16:00:00-07:00", 188.125, 0, 1],
["2017-09-20T17:00:00-07:00", 123.125, 0, 1],
["2017-09-20T18:00:00-07:00", 114.25, 0, 1],
["2017-09-20T19:00:00-07:00", 115, 0, 1],
["2017-09-20T20:00:00-07:00", 113.25, 0, 1],
["2017-09-20T21:00:00-07:00", 115.625, 0, 1],
["2017-09-20T22:00:00-07:00", 114.75, 0, 1],
["2017-09-20T23:00:00-07:00", 114, 0, 1],
["2017-09-21T00:00:00-07:00", 112.625, 0, 1],
["2017-09-21T01:00:00-07:00", 108.375, 0, 1],
["2017-09-21T02:00:00-07:00", 111.125, 0, 1]
];

console.log(arr[0]);

arr.shift();

console.log(arr[0]);




答案 1 :(得分:0)

您可以使用z myArray.data.splice(0, 1)删除第一个数组项,但错误告诉您正在尝试将数组方法应用于未定义的值。也许$ scope还没有收到价值

答案 2 :(得分:0)

.shift() is working fine. 

问题在于您的数组将要转移,检查myArray.data是否由数据组成,错误表示您正在尝试从未定义(空)对象移位值。

splice(0,1) also working fine
相关问题