jQuery通过索引获取数组的值

时间:2010-09-10 23:44:00

标签: jquery arrays indexing extend

使用jQuery,我试图通过使用索引获取fileTypes的值。我不知道如何做到这一点,但到目前为止,我已经尝试settings.fileTypes[0]这是行不通的。感谢任何帮助,谢谢!

    var defaults = {
        fileTypes : { 
            windows: 'Setup_File.exe',
            mac: 'Setup_File.dmg',
            linux: 'Setup_File.tar.gz',
            iphone: 'iPhone App'
        }
    },
        settings = $.extend({}, defaults, options);

2 个答案:

答案 0 :(得分:4)

fileTypes是一个Object,因此,它的属性不能通过索引号访问。

对象不保证任何已定义的顺序,因此如果您需要以索引顺序维护项目,则需要使用数组。

要获得给出示例的第一项,您可以按名称进行:

settings.fileTypes.windows;  // will return 'Setup_File.exe'

要存储为可通过索引检索其项目的数组,请尝试以下方法:

var defaults = {
        fileTypes : [
            'Setup_File.exe',
            'Setup_File.dmg',
            'Setup_File.tar.gz',
            'iPhone App'
        ]
    },

settings.fileTypes[0];  // will return 'Setup_File.exe'

或者你可以做一个对象数组,但我不认为这是你所追求的:

var defaults = {
        fileTypes : [ 
            {type: 'Setup_File.exe'},
            {type: 'Setup_File.dmg'},
            {type: 'Setup_File.tar.gz'},
            {type: 'iPhone App'}
        ]
    },

settings.fileTypes[0].type;  // will return 'Setup_File.exe'

答案 1 :(得分:0)

如果您的应用程序设计允许,也许您可​​以使用解决方法。 它有时候对我有用。

var defaults = {
    fileTypes : {
        0: {
          key: 'windows',
          file: 'Setup_File.exe'
        },
        1: {
          key: 'mac',
          file: 'Setup_File.dmg'
        }
    }
};

通过这种方式,您可以按索引访问第一级元素(按特定顺序),如果您需要示例中的密钥,它们仍然存在。

相关问题