【问题标题】:javascript index of object is string and not int对象的javascript索引是字符串而不是int
【发布时间】:2012-07-05 12:49:28
【问题描述】:

我想知道为什么我在 pages 对象(见下文)中的 pageCounter 被视为字符串而不是 int? 为什么javascript不解释变量,而是把变量名当作文字字符串使用?

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:[{story}, {story}, {story}], 1:[{story}, {story}]}];

标签: javascript string object counter


【解决方案1】:

对象字段名称——这就是{pageCounter:stories[i]} 中的pageCounter——总是字符串(或类似字符串)。 {pageCounter:stories[i]} 中的 pageCounter 与您正在递增的 pageCounter 无关。

【讨论】:

  • 所以对象字段名永远不能是整数? pageCounter 是循环之前定义的全局变量 ...
  • 好吧,如果你把它用作数组的话。但是你不能按照你的方式设置它。请参阅丹尼斯的回答。
【解决方案2】:

如果您想使用pageCounter 作为变量而不是名称,则需要这样做:

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

【讨论】:

  • mmm...不确定这是否能解决问题,因为最终我要寻找的是:[{0:[{story}, {story}, {story}], 1:[{story}, {story}]}]; 我是否朝着正确的方向前进?我需要一个包含几个对象数组的对象...
猜你喜欢
  • 2019-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-13
相关资源
最近更新 更多