[英]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 ...)
將會失敗,因為這會進行一次對象迭代,因此會抓取數組中的許多其他元素,如length
, indexOf
等。
請嘗試使用傳統的for
循環:
for (var i = 0; i < valuesArr.length; i++) {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.