2012-07-05 78 views
-2

我想知道爲什麼我的pageCounter在頁面對象(見下文)被視爲一個字符串而不是int? 爲什麼javascript不解釋變量並將變量的名稱用作文字字符串?對象的javascript索引是字符串,而不是int

for (var i in stories){ 
     //reset the counter when it hits the number of stories per page 
     if (counter >= divsByPage) { 
      counter = 1; 
      pageCounter++; 
     } 

     //turn all the stories off 
     //stories[i].style.display = "none"; 

     //insert a new story under a page array 
     pages.push({pageCounter:stories[i]}); 

     counter++; 
    } 

console.log(pages[1]);輸出Object { pageCounter=[1]}

+0

它應該輸出什麼? – 2012-07-05 12:52:18

+0

提供更多信息! – Amberlamps 2012-07-05 12:52:44

+0

是什麼讓你覺得它是一個字符串? – Utkanos 2012-07-05 12:52:46

回答

0

對象的字段名稱 - 這正是pageCounter{pageCounter:stories[i]}是 - 總是字符串(或字符串-喜歡)。 {pageCounter:stories[i]}中的pageCounter與您正在增加的pageCounter無關。

+0

因此,對象字段名永遠不可以是整數? pageCounter是循環之前的全局定義變量... – royco 2012-07-05 13:00:03

+0

那麼,如果你使用它作爲數組。但你無法按照自己的方式進行設置。見丹尼斯的答案。 – Supr 2012-07-05 13:08:02

0

你需要做這個,如果你想使用pageCounter作爲變量,而不是一個名字:

var object = {}; 
object[pageCounter] = stories[i]; 
pages.push(object); 
+0

mmm。 ..不知道這是否能解決問題,因爲最終我所尋找的是類似於:[{0:[故事},{故事},{故事}],1:[{故事},{故事}]}];'我正朝着正確的方向走?我需要一個包含幾個對象數組的對象... – royco 2012-07-05 13:03:17

相關問題