繁体   English   中英

当我的配置文件中有一个普通数组时,我应该如何 go 关于使用 jQuery 扩展?

[英]How should I go about using jQuery extend when my config file has a normal array in it?

似乎$.extend仅使用其输入的键来确定要覆盖的内容。 所以当我的配置看起来像这样

var config = {
    "numeric" : false,
    "keycode_whitelist" : [
        37, 39, // Left, right
        9,      // Tab
        17,     // Ctrl
        116     // F5
    ]
};

并且扩展了更多的键码以添加到白名单中,即使它们是不同的值,扩展也会用新的键码一一覆盖默认值。

我正在考虑通过键入37: 37, 39: 39等键来解决这个问题。我想要一个不会强迫我弄乱配置语法的解决方案。

您可能想要使用合并而不是扩展:

var config = {
    "numeric": false,
    "keycode_whitelist": [
        37, 39, // Left, right
        9, // Tab
        17, // Ctrl
        116 // F5
    ]
};

var custom = {
    "somevalue": "some other things",
    "keycode_whitelist": [
        1, 2, 3
        ]
};
var newopts = $.extend({}, config, custom);
newopts.keycode_whitelist = $.merge(custom.keycode_whitelist, config.keycode_whitelist);

演示: http://jsfiddle.net/3Q4cF/2/

更新:

要合并每个数组:

$.each(config, function(key, obj){
    if($.isArray(obj)) {
        if(custom[key]) {
           newopts[key] = $.merge(config[key], custom[key]);
        }
    }
} );

http://jsfiddle.net/3Q4cF/5/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM