看看這個plugin/gist from KnightCoder
下面是這個插件的實際源代碼。
/*
* DictionaryKnight v1.0 - A very simple teeny-tiny dictionary class.
* * @ Developer : https://github.com/KnightCoder
* * * You can add an item into the dictionary
* * * You can even directly add a collection of items
* * * You can get length of the items in the dictionary
* * * You can easily parse and get the items in the dictionary
* * * Very small, fast and efficient
*/
var DictionaryKnight = function() { };
DictionaryKnight.prototype = {
getLength: function() { return Object.keys(this).length },
add: function (key, value) {
this[key] = value;
return this;
},
addCollection: function (arr) {
for (var i = 0; i < arr.length; i++) {
this.add(arr[i][0], arr[i][1]);
}
return this;
}
}
它有一個很小的字典功能。
您可以使用它像這樣:
var dict = new DictionaryKnight();
dict.add("en", { "language": "English", "country": "Great Britain", "sample": "This is english" });
dict.add("hi", { "language": "Hindi", "country": "India", "sample": "यह हिन्दी है" });
var arr = [];
arr.push(["es", { "language": "Spanish", "country": "Spain", "sample": "Esto es español" }]);
arr.push(["cn", { "language": "Chinese", "country": "China", "sample": "這是中國" }]);
dict.addCollection(arr);
console.log("Total data : " + dict.getLength());
for (var i = 0; i < Object.keys(dict).length; i++) {
console.log(Object.keys(dict)[i]);
console.log(dict[Object.keys(dict)[i]]);
console.log("-----");
}
在第一種方法,你可以插入鍵值格式的數據,並在第二個方法,你可以在2維陣列格式添加數據的集合。 您也可以像上面的示例中所示組合使用這兩種方法。
完美,正是我一直在尋找。不知道[]和{}之間的區別 – Whistler