2012-06-05 28 views
1

我在數組中放入了一些日期,並希望在該數組中有第二個「層」來保存與該日期關聯的訂單號。它似乎工作正常,但是當我在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 

回答

2

你與做什麼0是將一個屬性添加到Date對象,而不是將一個元素添加到數組中。

將元素添加到陣列,使用方法:

dateArray[u][1] = order_number; 
+0

'dateArray [u] ['order_number'] = order_number;'與說'dateArray [u] .order_number = order_number;'相同,意味着對象'dateArray [u]'的屬性'order_number'被設置到你的變量'order_number'的值。 – Wex

+0

@Wex所以有什麼辦法給它一個字符串的索引,還是它必須是一個數字索引?另外,我這樣做的方式(我並不是說它是好的或正確的)的確如我所期望的那樣在Chrome控制檯中顯示出來。任何想法爲什麼?謝謝。 – 1252748

+0

數組索引必須是數字。你所做的不一定是錯誤或不好的,這可能不是你所想的。控制檯可能會說,「我在這裏有一個數組,所以我會循環它...這個對象是一個日期...它有一個toString方法...所以我會調用該方法並顯示結果。「這不會尋找你可能已經添加到它的隨機屬性 –

0

如果valuesArr是一個數組,然後使用for (... in ...)因爲這樣做一個對象迭代將失敗,並且因此將抓住大量陣列的其它元件的像lengthindexOf,等等等等

嘗試使用傳統for循環,而不是:

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

雖然你說得對,'換in'是不正確的工具,它不會搶本地''一樣.length' Array.prototype'性質,因爲他們是不可枚舉。只會遇到枚舉擴展。 – 2012-06-05 18:55:17

+0

@amnotiam肯定會變成for循環。假設它實際上是for-in循環會抓住這些其他元素,而for-in循環不會呢?感謝您幫助解決這個問題。 – 1252748

+0

@thomas:'for-in'枚舉所有可枚舉的屬性,並不保證任何特定的順序。如果將可枚舉的屬性添加到'Array.prototype','for-in'也會遇到這些。標準'for'循環對數字索引的迭代是正確的,因爲它強制執行特定的屬性和順序。 – 2012-06-05 21:10:22

2

不要絕對地信任開發商控制檯。沒有「正確的」打印,因爲沒有標準。

如果Chrome決定不在對象上顯示自定義屬性,那取決於Chrome。 只要你的價值顯示在那裏,並有明確的測試,那就是最重要的。


FWIW,你可能會得到...更理想的結果

console.dir(dateArray) 

console.dir方法會給你擴展的對象,這樣可以向下鑽取,看看你的自定義屬性。

+0

@wex這個console.dir選項顯示了一切,完全如我所料。如何證明它正在爲日期方法添加屬性。對不起,但我真的很困惑它是如何發生的..我也有點擔心,我以前做過這個,也許只是鉻的控制檯,這是理解我打算... – 1252748