2013-02-13 74 views
1

見JavaScript註釋JavaScript設置變量導致或沒有

var SearchResult = { 
    googleApiKey: "", 
    googleUrl: "https://www.googleapis.com/shopping/search/v1/public/products?key={key}&country={country}&q={query}&alt=atom", 
    country: "UK" 
    Query: function(args) 
    {  
     // Is there a way to do this in a less messy way? 
     args.googleApiKey ? : this.googleApiKey = args.googleApiKey : null; 
     args.country? : this.country = args.country: null; 
    } 
} 

基本上,如果有人對我的對象屬性提供了一個新的價值,我想它來設置它,否則只是繼續使用提供的缺省值。

我知道位運算符是選擇選擇的好選擇,但我不知道如何將它轉換爲javascript?

+0

你做錯了。你的意思是'args.googleApiKey = this.googleApiKey? this.googleApiKey:null;'或使用||如下面的答案所示 – mplungjan 2013-02-13 10:49:18

回答

3

在JavaScript中,你可以使用以下命令:

// thingYouWantToSet = possiblyUndefinedValue || defaultValue; 
this.googleApiKey = args.googleApiKey || ''; 

需要說明的使用是,如果第一個值是零或空字符串,你最終會使用默認值,這可能不是你打算什麼。例如

var example = ''; 
var result = example || 'default'; 

雖然設置了示例,但您將以'默認'字符串結束。如果這導致你的問題,切換到:

(typeof args.googleApiKey === 'undefined') 
    ? this.googleApiKey = 'default' 
    : this.googleApiKey = args.googleApiKey; 

如果你重複自己很多,你可以使用幫助函數使這個更清潔。

var mergedSetting = function (setting, default) { 
    return (typeof setting === 'undefined') ? default : setting; 
} 

this.googleApiKey = mergedSetting(args.googleApiKey, 'default value'); 
+0

第二個正是我打算:)...所以如果我返回null,它會將變量設置爲null ..我需要做的是:... this.googleApiKey = args.googleApiKey || this.googleApiKey ....聲音正確嗎?或者返回null只返回默認值? – Jimmyt1988 2013-02-13 10:59:42

+1

'this.googleApiKey = args.googleApiKey || this.googleApiKey;'如果'args.googleApiKey'爲undefined,null,false,0或''',則會將其保留爲當前值。如果'this.googleApiKey'已更新爲'Hello World',則它將保持爲'Hello World'。如果您想將其恢復爲默認值,請在代碼中提供如下代碼:'this.googleApiKey = args.googleApiKey || '';' – Fenton 2013-02-13 11:02:59

+0

謝謝。這將做到這一點:) – Jimmyt1988 2013-02-13 11:06:28

4
args.googleApiKey = args.googleApiKey || this.googleApiKey; 
args.country = args.country || this.country; 

不知道我明白你的問題;

+0

+1你擊敗了我。在OP的情況下,我認爲他們希望設置'this.googleApiKey',因爲這是問題中設置的內容。 – Fenton 2013-02-13 10:51:14

+0

this.googleApiKey = args.googleApiKey || this.googleApiKey ...也可以是this.googleApiKey = args.googleApiKey || null ...或者這會使this.googleApiKey = null? – Jimmyt1988 2013-02-13 11:03:31

+0

你是對的,這將使this.googleApiKey =空(注意,不是在如果args.googleApiKey是其中之一:0,'',假,未定義) – karaxuna 2013-02-13 11:07:15