[英]How should I go about using jQuery extend when my config file has a normal array in it?
Seems $.extend
uses only the keys of its input to determine what to overwrite.似乎
$.extend
仅使用其输入的键来确定要覆盖的内容。 So when my config looks like this所以当我的配置看起来像这样
var config = {
"numeric" : false,
"keycode_whitelist" : [
37, 39, // Left, right
9, // Tab
17, // Ctrl
116 // F5
]
};
and is extended with more keycodes to add to the whitelist, extend simply overwrites the defaults with the new keycodes one by one even though they are different values.并且扩展了更多的键码以添加到白名单中,即使它们是不同的值,扩展也会用新的键码一一覆盖默认值。
I'm thinking about solving this problem by typing the keys like this 37: 37, 39: 39
etc. I would love a solution that doesn't force me to mess up the syntax of my configuration though.我正在考虑通过键入
37: 37, 39: 39
等键来解决这个问题。我想要一个不会强迫我弄乱配置语法的解决方案。
You might want to use merge instead of extend:您可能想要使用合并而不是扩展:
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);
Demo: http://jsfiddle.net/3Q4cF/2/演示: http://jsfiddle.net/3Q4cF/2/
Update:更新:
To merge every single array:要合并每个数组:
$.each(config, function(key, obj){
if($.isArray(obj)) {
if(custom[key]) {
newopts[key] = $.merge(config[key], custom[key]);
}
}
} );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.