[英]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]);
}
}
} );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.