4

我想弄清楚如何在 javascript 中执行 C#“函数”,但没有运气!?

这是C#:

var parameters = new Dictionary<string,string>
{
    { "link", "http://mysite.com" },
    { "name", "This is an test" }
};

我想我必须使用“新数组”但不知道该怎么做?

任何帮助表示赞赏并提前感谢:-)

4

5 回答 5

3

这是一个很好的解释:JavaScript Associative Arrays Demystified

var parameters = new Array();
parameters['link'] = 'http://mysite.com';
parameters['name'] = 'This is an test';
于 2013-08-28T14:25:08.873 回答
3

在 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";

此示例显示字典(对象)的值(字段值)通常通过使用点表示法编写键(字段名称)来访问,但您也可以使用索引表示法,如 C# 字典的情况。请注意,JavaScript 是一种动态语言,因此键和值的类型可以是任何类型。所以你可以定义一个像这样的字典(对象):

var parameters = {
  link: "http://mysite.com",
  name: "This is an test",
  id: 3,
  4: "$#!+",
  5: 123456
};

值(字段值)也可以是其他对象或函数。如果一个值是一个函数,它被称为 JavaScript 对象的一个​​方法

=== 更新 ===

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;
}());

测试代码:

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());

控制台输出(按 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 
于 2013-08-28T14:24:37.130 回答
1

只需使用一个对象:

var parameters = {
    "link": "http://mysite.com",
    "name": "This is an test"
};
于 2013-08-28T14:25:52.700 回答
1

像这样尝试怎么样: -

var dict = []; 

dict.push({
    key:   "Yourkeyvalue",
    value: "value"
});
于 2013-08-28T14:23:50.830 回答
0

给你(在我的脑海中,所以如果出现任何语法错误,请不要责怪我)。

这与您在 C# 中所做的方法完全相同,所以我认为您正在寻找它。

var parameters = [
    {
        key: 'link',
        value: 'http://mysite.com'
    },
    {
        key: 'name',
        value: 'This is an test'
    }];

或者这里是一个替代方案(可能更喜欢它,取决于你的编码风格)

创建一个数组并在之后添加项目。

var parameters = [];
parameters.push(
    {
        key: 'link',
        value: 'http://mysite.com'
    },
    {
        key: 'name',
        value: 'This is an test'
    });
于 2013-08-28T14:29:26.010 回答