从Javascript数组中抓取

时间:2014-12-07 03:04:27

标签: javascript arrays

所以我试图创建一个从数组中获取type_name的变量。

这是我的阵列。

var customIcons = {
        ItemI: {
            icon: 'http://...'
            type_name: 'East'
        },
        ItemII: {
            icon: 'http://...'
            type_name: 'West'
        },
        ItemIII: {
            icon: 'https:...'
            type_name: 'North'

        },
        question: {
            icon: 'https:...'
            type_name: 'South'

        }

}

这是我想要创建的变量。我知道php正确传递,但我不知道为什么它没有从数组中获取相应的type_name:

   var buttonText= customIcons[<?php echo $type; ?>].type_name;

当我尝试使用变量时,我得到一个无法读取属性'type_name'的undefined。

真诚感谢您的帮助!非常感谢。

3 个答案:

答案 0 :(得分:1)

您需要将其重写为

   var buttonText= customIcons['<?php echo $type; ?>'].type_name;

查看' '周围的<?php ?>,否则将其解析为js变量

答案 1 :(得分:0)

我想你忘记了引号。 var buttonText= customIcons['<?php echo $type; ?>'].type_name;

答案 2 :(得分:0)

我不了解PHP,但这里出了什么问题

你的JSON:你的逗号丢失了

var customIcons = {
        item1: {
            icon: 'http://...',
            type_name: 'East'
        },
        item2: {
            icon: 'http://...',
            type_name: 'West'
        },
        item3: {
            icon: 'https:...',
            type_name: 'North'

        },
        question: {
            icon: 'https:...',
            type_name: 'South'

        }
};

console.log(customIcons.item1.icon);

然后你的JSON结构不理想

应该是

var customIcons = [


           {
                id:"item1",
                icon: 'http://...',
                type_name: 'East'
            },
            {
                id:"item2",
                icon: 'http://...',
                type_name: 'West'
            },
            item: {
                id:"item3",
                icon: 'https:...',
                type_name: 'North'

            },
           {
                id:"item4",  
                icon: 'https:...',
                type_name: 'South'

            }
]

Then you can parse this easily using for loop
相关问题