2012-07-05 75 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

相关问题