简体   繁体   English

这两种在JavaScript中创建数组列表的方法有什么区别?

[英]What is the difference between these 2 ways of creating a list of arrays in JavaScript?

How do I dynamically create a list of arrays in JavaScript, that actually shows up in the Developer console as a list of arrays? 如何在JavaScript中动态创建数组列表,实际上在Developer Console中显示为数组列表?

Just rephrased this question; 只是改写了这个问题; there are plenty of examples how to do this, and my code is working, but I'm getting 2 very different results from these 2 methods: 有很多例子如何做到这一点,我的代码正在运行,但我从这两种方法得到2个非常不同的结果:

I tried this: 我试过这个:

var volume = [];
for (i = 0; i < json.length; i++) {
    var item = new Array(2);
    item[0] = json[i].json_date;
    item[1] = json[i].volume;
    volume.push(item);
    }

So, this code works, and seems to create an array of arrays, but in the developer console the result of console.log(typeof volume[0]) is undefined. 因此,此代码有效,并且似乎创建了一个数组数组,但在开发人员控制台中,console.log(typeof volume [0])的结果未定义。

If I create the array manually, it works much better: 如果我手动创建数组,它会更好用:

var volume = [
    [1313964000000,23.17],
    [1314050400000,23.78],
    [1314741600000,25.24],
    [1314828000000,24.77],
    [1440021600000,82.69]
];

Now console.log(typeof volume[0]) is object. 现在console.log(typeof volume [0])是对象。 And console.log(volume) results in: (5) [Array(2), Array(2), Array(2), Array(2), Array(2)]. 并且console.log(卷)导致:(5)[Array(2),Array(2),Array(2),Array(2),Array(2)]。 That's what I need, not just []. 这就是我需要的,而不仅仅是[]。

I've spent the entire day searching for answers, and have tried many variations of this code, but can't seem to find code that will dynamically create that volume array to correctly show up as an array of arrays. 我花了一整天时间寻找答案,并尝试了很多代码,但似乎无法找到动态创建该卷数组的代码,以正确显示为数组数组。

Has anyone else run into this? 有没有其他人遇到这个?

Here is the full code: 这是完整的代码:

var volume = [];

fetch("http://localhost:3000/api/v1/TSLA").then(function(response) {
    if(response.ok) {
        response.json().then(function(json) {
            for (i = 0; i < Object.keys(json).length; i++){
                volume.push(new Array(json[i].json_date, json[i].volume));
                }

            });
        } else {
            console.log('Network request failed with response ' + 
response.status + ': ' + response.statusText);
        }
        });

        console.log(volume);

So, the answer from oknawe helped me to solve this problem; 所以,oknawe的答案帮助我解决了这个问题; however in a way the question has still not been answered, because the volume array is only usable inside that fetch function. 但是在某种程度上问题仍然没有得到解答,因为卷数组只能在该获取功能中使用。 Later in the code, the data is still there, but individual elements test as undefined... 稍后在代码中,数据仍然存在,但是单个元素测试为未定义的...

That should work fine, assuming the variable json is structured as you expect. 假设变量json的结构符合您的预期,那应该可以正常工作。 You can also try: 你也可以尝试:

let volume = json.map((i) => [i.json_date, i.volume]);

(Provided your environment lets you use ES6.) (假设您的环境允许您使用ES6。)

Instead of manually looping over the array, you can iterate over the contents of the array with the map function. 您可以使用map函数迭代数组的内容,而不是手动循环遍历数组。

The length of a JSON object will be undefined since objects do not have a length value. 由于对象没有length值,因此JSON对象的length将是undefined You can use Object.keys to get size but that won't do you much good since object values cannot be accessed by index: 您可以使用Object.keys来获取大小,但由于索引无法访问对象值,因此这对您没有多大好处:

var volume = [];
for (i = 0; i < Object.keys(json).length; i++) {
    // can't access using json[i] here
}

However, you can use Object.keys(json) or Object.values(json) and do something like below: (you'll need to have code inside the json callback) 但是,您可以使用Object.keys(json)Object.values(json)并执行以下操作:( 您需要在json回调中包含代码)

let volume = [];
fetch('/api/foo/bar').then((data) => {
    return data.json();
}).then((json) => {
    console.log(json);
    Object.keys(json).forEach((obj) => {
        // obj = {"json_date": 1313964000000, "volume": 23.17, ...}
        console.log(obj);
        volume.push(new Array(obj["json_date"], obj["volume"]));
    });
    console.log(volume);
}).catch((e) => {
    console.error('There was a problem with the request');
})

Thanks to oknawe, I got it working. 感谢oknawe,我得到了它的工作。 Using that code works, provided I use that volume array inside the fetch code. 使用该代码的工作,提供我用取出码内部的容积阵列。 Outside that, the volume array still contains data, but individual elements are undefined. 除此之外,卷阵列仍包含数据,但未定义各个元素。 Many thanks to everyone who posted here! 非常感谢发布在这里的所有人!

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

相关问题 这两种在javascript中创建类的方法之间的区别 - difference between these 2 ways of creating a class in javascript JavaScript数组声明方式的区别 - JavaScript arrays declaration ways difference 这两种创建对象文字的不同方式有什么区别 - What is the difference between these two different ways of creating an object literal 这两种在Javascript中创建“私有”属性的方式之间的区别 - difference between these two ways of creating a 'private' property in Javascript 这两个Javascript数组有什么区别? - What is the difference between these two Javascript arrays? JavaScript 数组的“in 运算符”和“includes()”有什么区别 - What is the difference between "in operator" and "includes()" for JavaScript arrays 这两种从Javascript模块导出的方式之间有什么区别? - What is the difference between these 2 ways of exporting from a Javascript module? 用Javascript定义对象方法的两种方式有什么区别? - What is the difference between two ways of defining object methods in Javascript? 通过javascript为HTML元素赋值的方式有什么区别? - what is the difference between ways of assigning values to HTML elements via javascript? 在javascript对象中创建函数的不同方法有什么区别? - What is the difference between different ways to create a function inside javascript object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM