2013-07-21 32 views
0

我正在嘗試使我的對象列表中允許的選項的預設列表。這裏是代碼在對象中預設選項並查看它是否不存在於允許的屬性中

var a = function(cmd, options){ 
    var objList = [options.search ,options.demand]; 

    if(!(options in objList)){ 
     console.warn('Not an Allowed * in the options Property'); 
     } 
}; 

,或者我應該做的

var a = function(cmd, options){ 
    var objList = [search , demand]; 

    if(!(options in objList)){ 
     console.warn('Not an Allowed option in the options Property'); 
     } 
}; 

基本上就是我想要做的是設置searchdemand被允許的選項中選擇屬性,以便最遲可以做

a('cmd',{ 
    search:'', 
    demand:function() { 
    alert('Hello'); 
    }, 
    //warn that the next option is not allowed 
    quote: function() { 
    alert('quote of user'); 
    } 
    }); 

如果您無法理解我所問的問題,請提問,我會盡我所能解釋更多。

也許寫這樣會更好?

var a = function(cmd, options){ 
    options = { 
    theme: function(color) { 
    $('body').css('backgroundColor',color); 
    }, 
    color:'' 
    }; 
}; 

a('cmd',{ 
    theme:'#000'//though this is not working? 
}); 
+0

爲什麼你需要這個?將參數傳遞給對象的想法是,它允許您選擇要在函數中使用哪個參數,您可以簡單地忽略'options'對象中的額外屬性。 – Teemu

+0

那麼,因爲我不想使用額外的選項。順便說一句,我是新來的東西。我通常使用多個對象符號來創建我需要的代碼,但我想創建一個深度對象。也許我可以用我的代碼做一些不同的事情?通過可能使得'options = {//更深入的對象列表在這裏?\\};'以便在代碼內部執行'('cmd',{theme:'',color:''等) );'?? – EasyBB

+0

這個......你只能使用你所需要的'options'的屬性,如果有額外的屬性,它們在'a'執行後被垃圾回收。你編輯的例子不起作用,因爲你重寫了'options'參數。 – Teemu

回答

2

你可以檢查在options每個屬性對允許的選項數組是這樣的:

var a = function(cmd, options){ 
    var allowedOptions = ["search", "demand"]; 

    var hasDisallowedOptions = false; 

    for (option in options) { 
    if(allowedOptions.indexOf(option) === -1) { 
     hasDisallowedOptions = true; 
     break; 
    } 
    } 

    // if hasDisallowedOptions is true, then there is a disallowed option 
}; 

jsfiddle with a couple test cases/examples

+0

好吧,我會嘗試這種方式...如果它的工作Upvote和檢查 – EasyBB

+0

好吧,所以它的工作,雖然在嘗試多個不正確的選項只警告1個不正確的選項。我應該做選擇[選項]? – EasyBB

+0

你想列出所有不允許的選項嗎? –

1

傳遞參數中的對象的一個​​想法是,它可以讓你要選擇要在函數中使用哪個參數,可以簡單地忽略options對象中的其他屬性。因此,您不需要「過濾」參數的屬性。

讓我們假設你已經像這樣的功能:

var a = function (cmd, options) { 
    var theme = { 
     backgroundColor: options.bgColor, 
     color: options.color 
    } 
    // Do something with theme 
    // Notice also, that there was no use for options.extra in this function 
} 

然後調用a這樣的:

a('cmd', { 
    bgColor: '#ff0', 
    color: '#000', 
    extra: 'This is an extra property' 
}); 

現在你可以看到,extraa在所有使用,但它是作爲參數傳遞給a的匿名對象的屬性。傳遞給a的所有參數都是垃圾收集,除非您不打算創建閉包,即從a返回本地值或函數。

相關問題