我在數組中放入了一些日期,並希望在該數組中有第二個「層」來保存與該日期關聯的訂單號。它似乎工作正常,但是當我在chrome控制檯中輸出數組時,我只能看到第一個日期數組。如果我手動訪問console.log(dateArray[1]['order_number']);
,我會看到預期的信息。我沒有正確構建這個數組嗎?javascript數組未正確打印到控制檯
謝謝!
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;'與說'dateArray [u] .order_number = order_number;'相同,意味着對象'dateArray [u]'的屬性'order_number'被設置到你的變量'order_number'的值。 – Wex
@Wex所以有什麼辦法給它一個字符串的索引,還是它必須是一個數字索引?另外,我這樣做的方式(我並不是說它是好的或正確的)的確如我所期望的那樣在Chrome控制檯中顯示出來。任何想法爲什麼?謝謝。 – 1252748
數組索引必須是數字。你所做的不一定是錯誤或不好的,這可能不是你所想的。控制檯可能會說,「我在這裏有一個數組,所以我會循環它...這個對象是一個日期...它有一個toString方法...所以我會調用該方法並顯示結果。「這不會尋找你可能已經添加到它的隨機屬性 –