Quantcast
Channel: 黑暗執行緒
Viewing all articles
Browse latest Browse all 2311

在JavaScript模擬C# Dictionary、LINQ Where、Select與OrderBy

$
0
0

一週內被兩位同事問到幾乎相同的問題,這一定是天意!趕緊寫篇FAQ以免天公伯不開心~

【問題】

  • 用JavaScript要怎麼實現Dictionary<string, T>?
  • JavaScript有沒有類似LINQ Where()、Select()、OrderBy()的東西?

回答第一個問題,JavaScript物件本身就具備Dictionary<string, T>的特性,範例如下:

<!DOCTYPEhtml>
<html>
<head>
 
<metacharset="utf-8">
<metaname="viewport"content="width=device-width">
<title>JS Dictionary&lt;string, T&gt;</title>
</head>
<body>
 
<scriptsrc="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
function Player(Id, Name, RegDate, Score) {
this.Id = Id;
this.Name = Name;
this.RegDate = RegDate;
this.Score = Score;
    }
var p1 = new Player("P1", "Jeffrey", new Date(1900, 0, 1), 32767);
var p2 = new Player("P2", "Darkthread", new Date(2016, 6, 2), 65536);
//使用JavaScript物件模擬Dictionary<string, Player>
var dict = {};
//加入或指定key為P1的內容
    dict["P1"] = p1;
    dict["P2"] = p2;
//讀取key為P1的項目
    console.log("P1.Name = " + dict["P1"].Name);
//檢查key是否存在
if (dict["P1"]) console.log("P1存在");
if (!dict["Q1"]) console.log("Q1不存在"); 
 
//模擬Dictionary<string, T>.Keys
//IE7、8相容
var keys = [];
for (var key in dict) keys.push(key); 
    console.log(keys);
//IE9+及其他瀏覽器
    console.log(Object.keys(dict)); 
//模擬Dictionary<string, T>.Values
var values = $.map(keys, function(key) { return dict[key] });
    console.log("values[0].Name=" + values[0].Name);
    console.log("values[1].Name=" + values[1].Name);
//移除指定key值項目
    delete dict["P1"];
if (!dict["P1"]) console.log("P1已移除");
</script>
</body>
</html>

執行結果:Live Demo

"P1.Name = Jeffrey""P1存在""Q1不存在"
["P1", "P2"]
["P1", "P2"]"P1已移除""P1.Name = Jeffrey""P1存在""Q1不存在"
["P1", "P2"]
["P1", "P2"]"values[0].Name=Jeffrey""values[1].Name=Darkthread""P1已移除"

補充,在TypeScript如要宣告Dictionary<string, Player>強型別,寫法為var dict: { ["key": string]: Player } = {};

問題二,JavaScript能否做到LINQ Where() Select() OrderBy()的效果?

類似需求我慣用jQuery.grep()jQuery.map()搞定,排序則可用JavaScript Array本身的sort()方法,但sort()會改掉陣列本身的順序,若要比照OrderBy()的效果,得先用.slice(0)另建一個複本,示範如下:

<!DOCTYPEhtml>
<html>
<head>
 
<metacharset="utf-8">
<metaname="viewport"content="width=device-width">
<title>JS LINQ Where(), Select() and OrderBy()</title>
</head>
<body>
 
<scriptsrc="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
function Player(Id, Name, RegDate, Score) {
this.Id = Id;
this.Name = Name;
this.RegDate = RegDate;
this.Score = Score;
    }
var p1 = new Player("P1", "Jeffrey", new Date(1900, 0, 1), 32767);
var p2 = new Player("P2", "Darkthread", new Date(2016, 6, 2), 65536);
//用陣列模擬List<Player>
var list = [p1, p2];
//Where(o => o.Score > 255)
var res = $.grep(list, function(o) { return o.Score > 255 });
    console.log("Where(o => o.Score > 255).Count=" + res.length);
//Select(o => new { PlayerId = o.Id, PlayerName = o.Name })
var res = $.map(list, function(o) { return { PlayerId: o.Id, PlayerName: o.Name }; });
    console.log("Select(o => new { PlayerId = o.Id, PlayerName = o.Name }).Count=" + res.length);
    console.log("res[0].PlayerId=" + res[0].PlayerId);
    console.log("res[1].PlayerName=" + res[1].PlayerName);
//OrderBy(o => o.Name)
//OrderBy不更動List<T>順序,在JavaScript要用slice(0)先複製新陣列物件
//以免sort影響原陣列排序
var sorted = list.slice(0).sort(function(a, b) {
if (a.Name === b.Name) return 0;
return (a.Name < b.Name) ? -1 : 1;
    });
    console.log("sorted[0].Name=" + sorted[0].Name);
    console.log("sorted[1].Name=" + sorted[1].Name);
//OrderByDecending(o => o.Score)
    sorted = list.slice(0).sort(function(a, b) {
if (a.Score === b.Score) return 0;
return (a.Score > b.Score) ? -1 : 1;
    });
    console.log("sorted[0].Score=" + sorted[0].Score);
    console.log("sorted[1].Score=" + sorted[1].Score);    
</script>
</body>
</html>

執行結果:Live Demo

"Where(o => o.Score > 255).Count=2""Select(o => new { PlayerId = o.Id, PlayerName = o.Name }).Count=2""res[0].PlayerId=P1""res[1].PlayerName=Darkthread""sorted[0].Name=Darkthread""sorted[1].Name=Jeffrey""sorted[0].Score=65536""sorted[1].Score=32767"

以上範例使用jQuery.grep()模擬Where()、用jQuery.map()模擬Select(),而在ECMAScript 5規格,JavaScript Array已加入foreachfiltermap等方法,可以取代jQuery的.each()、.grep()及.map(),但存在IE7/IE8不支援的限制需要留意。ES5內建的filter()與map()用起來跟jQuery版差不多,換用工程不大,以下為改寫範例: Live Demo

//Where(o => o.Score > 255)
var res = list.filter(function(o) { return o.Score > 255 });
    console.log("Where(o => o.Score > 255).Count=" + res.length);
//Select(o => new { PlayerId = o.Id, PlayerName = o.Name })
var res = list.map(function(o) { return { PlayerId: o.Id, PlayerName: o.Name }; });
    console.log("Select(o => new { PlayerId = o.Id, PlayerName = o.Name }).Count=" + res.length);
    console.log("res[0].PlayerId=" + res[0].PlayerId);
    console.log("res[1].PlayerName=" + res[1].PlayerName);

最後,如果你覺得以上做法不夠原汁原味,還是想在JavaScript執行正統的LINQ方法,例如:

var queryResult = Enumerable.From(jsonArray)
    .Where(function (x) { return x.user.id < 200 })
    .OrderBy(function (x) { return x.user.screen_name })
    .Select(function (x) { return x.user.screen_name + ':' + x.text })
    .ToArray();

有個Open Source專案-linq.js可以實現以上夢想。不過,該專案已有段時間未更新,採用前也應該入考量。而依我個人看法,既然在寫前端,不妨改變思維,依循JavaScript風格解決才是王道。既然已有簡便做法能滿足需求,硬要復刻還原過往的習慣,並不利於執行效能及團隊協作,用JavaScript簡便搞定還是較好的選擇。


Viewing all articles
Browse latest Browse all 2311

Trending Articles