使用 javascript 创建新字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18490614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create new Dictionary with javascript
提问by Mansa
I am trying to figure out how to do an C# "function" in javascript but am having no luck!?
我想弄清楚如何在 javascript 中执行 C#“函数”,但我没有运气!?
Here is the C#:
这是 C#:
var parameters = new Dictionary<string,string>
{
{ "link", "http://mysite.com" },
{ "name", "This is an test" }
};
I want to think that I have to use "new Array" but am not sure how to do this?
我想我必须使用“新数组”,但不知道该怎么做?
Any help is appreciated and thanks in advance :-)
任何帮助表示赞赏并提前致谢:-)
回答by kol
In JavaScript, every objectis a dictionary (an associative array). Your example can be written as an object literal:
在 JavaScript 中,每个对象都是一个字典(一个关联数组)。您的示例可以写为对象文字:
var parameters = {
link: "http://mysite.com",
name: "This is an test"
};
// Read access
console.log(parameters.link); // or:
console.log(parameters["link"]);
// Write access
parameters.link = "http://yoursite.com"; // or:
parameters["link"] = "http://yoursite.com";
parameters.status = "OK"; // or:
parameters["status"] = "OK";
This example shows that the values (field values) of the dictionary (object) are usually accessed by writing the key (field name) using dot notation, but you can also use the index notation, as in case of C# dictionaries. Note that JavaScript is a dynamic language, so the type of keys and values can be anything. So you can define a dictionary (object) like this one:
此示例显示字典(对象)的值(字段值)通常是通过使用点表示法编写键(字段名称)来访问的,但您也可以使用索引表示法,就像 C# 字典一样。请注意,JavaScript 是一种动态语言,因此键和值的类型可以是任何类型。所以你可以像这样定义一个字典(对象):
var parameters = {
link: "http://mysite.com",
name: "This is an test",
id: 3,
4: "$#!+",
5: 123456
};
The values (field values) can be other objects or functions, too. If a value is a function, it is called a methodof the JavaScript object.
值(字段值)也可以是其他对象或函数。如果一个值是一个函数,它就被称为JavaScript 对象的一个方法。
=== UPDATE ===
=== 更新 ===
Here is an approximation of the C# Dictionary<TKey,TValue>
class in JavaScript (the test page is here). This code works, but I strongly recommend doing things in JavaScript the JavaScript way: objects can be used directly as associative arrays, there is no real need to use such a wrapper!
这是Dictionary<TKey,TValue>
JavaScript 中C#类的近似值(测试页面在这里)。这段代码有效,但我强烈建议在 JavaScript 中以 JavaScript 的方式做事:对象可以直接用作关联数组,实际上没有必要使用这样的包装器!
var Dictionary = (function () {
function Dictionary() {
if (!(this instanceof Dictionary))
return new Dictionary();
}
Dictionary.prototype.Count = function() {
var key,
count = 0;
for (key in this) {
if (this.hasOwnProperty(key))
count += 1;
}
return count;
};
Dictionary.prototype.Keys = function() {
var key,
keys = [];
for (key in this) {
if (this.hasOwnProperty(key))
keys.push(key);
}
return keys;
};
Dictionary.prototype.Values = function() {
var key,
values = [];
for (key in this) {
if (this.hasOwnProperty(key))
values.push(this[key]);
}
return values;
};
Dictionary.prototype.KeyValuePairs = function() {
var key,
keyValuePairs = [];
for (key in this) {
if (this.hasOwnProperty(key))
keyValuePairs.push({
Key: key,
Value: this[key]
});
}
return keyValuePairs;
};
Dictionary.prototype.Add = function(key, value) {
this[key] = value;
}
Dictionary.prototype.Clear = function() {
var key,
dummy;
for (key in this) {
if (this.hasOwnProperty(key))
dummy = delete this[key];
}
}
Dictionary.prototype.ContainsKey = function(key) {
return this.hasOwnProperty(key);
}
Dictionary.prototype.ContainsValue = function(value) {
var key;
for (key in this) {
if (this.hasOwnProperty(key) && this[key] === value)
return true;
}
return false;
}
Dictionary.prototype.Remove = function(key) {
var dummy;
if (this.hasOwnProperty(key)) {
dummy = delete this[key];
return true;
} else
return false;
}
return Dictionary;
}());
Test code:
测试代码:
var d = new Dictionary(),
i,
keyValuePair;
console.clear();
// Adding new elements.
d.Add("key1", "value1");
d.Add("key2", "value2");
// This also works. There is no KeyNotFoundException,
// the key-value pairs are inserted silently.
d["key3"] = "value3";
d["key4"] = "value4";
// Getting the number of key-value pairs.
console.log("Count:", d.Count());
// Getting an array containing the keys.
console.log("Keys:", d.Keys());
// Getting an array containing the values.
console.log("Values:", d.Values());
// Iterating over the key-value pairs.
for (i = 0; i < d.KeyValuePairs().length; i += 1) {
keyValuePair = d.KeyValuePairs()[i];
console.log("#", i + 1, keyValuePair.Key, "=>", keyValuePair.Value);
}
// Determining whether the dictionary contains a given key.
console.log("key2?", d.ContainsKey("key2"));
console.log("keyhole?", d.ContainsKey("keyhole"));
// Determining whether the dictionary contains a given value.
console.log("value2?", d.ContainsValue("value2"));
console.log("valuable?", d.ContainsValue("valuable"));
// Removing a value with a given key.
console.log("Removing key2:", d.Remove("key2"));
console.log("Count after Remove():", d.Count());
console.log("Removing keyhole:", d.Remove("keyhole"));
console.log("Count after Remove():", d.Count());
// Clearing all key-value pairs.
d.Clear();
console.log("Count after Clear():", d.Count());
Console output (press F12):
控制台输出(按 F12):
Count: 4
Keys: ["key1", "key2", "key3", "key4"]
Values: ["value1", "value2", "value3", "value4"]
# 1 key1 => value1
# 2 key2 => value2
# 3 key3 => value3
# 4 key4 => value4
key2? true
keyhole? false
value2? true
valuable? false
Removing key2: true
Count after Remove(): 3
Removing keyhole: false
Count after Remove(): 3
Count after Clear(): 0
回答by RvdK
Here is a great explanation: JavaScript Associative Arrays Demystified
这是一个很好的解释:JavaScript Associative Arrays Demystified
var parameters = new Array();
parameters['link'] = 'http://mysite.com';
parameters['name'] = 'This is an test';
回答by mingos
Just use an object:
只需使用一个对象:
var parameters = {
"link": "http://mysite.com",
"name": "This is an test"
};
回答by Rahul Tripathi
How about trying like this:-
试试这样怎么样:-
var dict = [];
dict.push({
key: "Yourkeyvalue",
value: "value"
});
回答by Daniel Wardin
Here you go (off the top of my head so don't blame me for syntax errors if any come up).
给你(如果有语法错误,请不要责怪我)。
This is an exact same approach as you would have done in C# so I think you are looking for this.
这是一种与您在 C# 中所做的完全相同的方法,所以我认为您正在寻找这个。
var parameters = [
{
key: 'link',
value: 'http://mysite.com'
},
{
key: 'name',
value: 'This is an test'
}];
or here is an alternative (might prefer it, depending on your coding style)
或者这里有一个替代方案(可能更喜欢它,取决于你的编码风格)
Create an array and add the items in after.
创建一个数组并在之后添加项目。
var parameters = [];
parameters.push(
{
key: 'link',
value: 'http://mysite.com'
},
{
key: 'name',
value: 'This is an test'
});