繁体   English   中英

javascript数组无法正常打印到控制台

[英]javascript array not printing to console properly

我将一些日期放入一个数组中,并希望在该数组中有第二个“层”保存与该日期相关的订单号。 它似乎工作正常,但是当我在chrome控制台中打印出数组时,我只看到第一个日期数组。 如果我手动访问console.log(dateArray[1]['order_number']); ,我看到了预期的信息。 我没有正确构建这个数组吗?

谢谢!

    for ( var u in valuesArr ) {

        //store the text seperator between the information and the order it is associated with
        var sep = "?order_num=";

        //store the string from which the information and order number will be extracted
        var str = valuesArr[u];

        //location of seperator
        var start = str.indexOf("?order_num=");

        var order_number = str.substring(start+sep.length);

        var current_date = valuesArr[u].substring(0, start);

        //date goes into "current_date" array
        current_date = current_date.split(" / ");

        //fashion it into a javascript date
        //month needs one subtracted
        dateArray[u] = new Date ( current_date[2], current_date[0]-1, current_date[1]);

        /*
        *to identify from which order this date derives, an order_number slot is created
        *underneath the sorted date slot
        *this is done so that when the html is reformatted to re-order the dates
        *the content associated with this date can be 'brought along with' it
        *as the its parent div's id contains the order number
        */
        dateArray[u]['order_number'] = order_number;

    }
    console.log(dateArray)//only outputs the array of dates
    console.log(dateArray[1]['order_number']);//outputs the order number

你用dateArray[u]['order_number'] = order_number;做什么 正在向Date对象添加属性,而不是向数组添加元素。

要向数组添加元素,请使用:

dateArray[u][1] = order_number;

不要隐含地信任开发人员控制台。 没有“正确”的打印,因为没有标准。

如果Chrome决定不在对象上显示自定义属性,则由Chrome决定。 只要您的价值显示在那里进行明确的测试,那就重要了。


FWIW,你可能会得到更理想的结果......

console.dir(dateArray)

console.dir方法将为您提供可扩展对象,以便您可以向下钻取并查看自定义属性。

如果valuesArr是一个数组,那么使用for (... in ...)将会失败,因为这会进行一次对象迭代,因此会抓取数组中的许多其他元素,如lengthindexOf等。

请尝试使用传统的for循环:

for (var i = 0; i < valuesArr.length; i++) {
  // ...
}

暂无
暂无

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

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