看看这个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