小夥伴們在工做中會遇到這樣的場景:
有一組變量的值是根據其餘某個值來改變的,也就是一一對應,好比:編碼
var cityCode = "城市區號", cityName = "城市名稱", university = "最高學府", province = "所屬省份";
城市區號是具備惟一性的,而另外三個值和城市區號是已具備關聯性的。若是城市編號不肯定,但我們就得作判斷,通常有if...else,switch...case,以下:code
if( cityCode == "0755") { cityName = "深圳"; university = "深圳大學"; province = "廣東省"; } else if( cityCode == "010") { cityName = "北京"; university = "北京大學"; province = "北京市"; } else if( cityCode == "027") { cityName = "武漢"; university = "武漢大學"; province = "湖北省"; }
或者:ci
switch (cityCode) { case "0755" : cityName = "深圳"; university = "深圳大學"; province = "廣東省"; break; case "010" : cityName = "北京"; university = "北京大學"; province = "北京市"; break; case "027" : cityName = "武漢"; university = "武漢大學"; province = "湖北省"; break; }
還有一種方式:it
cityName = {"0755" : "深圳", "010" : "北京", "027" : "武漢"}[cityCode] || "沒有定義"; university = {"0755" : "深圳大學", "010" : "北京大學", "027" : "武漢大學"}[cityCode] || "沒有定義"; province = {"0755" : "廣東省", "010" : "北京市", "027" : "湖北省"}[cityCode] || "沒有定義";
相比上面兩種,這種方式的可讀性可能稍微差了那麼一點點,但是簡潔了許多。
但仍是重複了一些,根據城市編碼取了三個變量的值,結果每取一次,就要要寫一次城市編碼,反而不那麼簡潔了。變量
最後一種方式:vi
var cityMode = { "0755" : { cityCode : "0755", cityName : "深圳", university : "深圳大學", province : "廣東省" }, "010" : { cityCode : "010", cityName : "北京", university : "北京大學", province : "北京市" }, "027" : { cityCode : "027", cityName : "武漢", university : "武漢大學", province : "湖北省" } }; cityName = cityMode[cityCode].cityNanme; university = cityMode[cityCode].university; province = cityMode[cityCode].province;
這種方式,應該也仍是不錯的,可讀性強,但貌似寫的代碼多了一點。co
以上,歡迎各位朋友指正,也但願能看到更好更簡潔的寫法。cas