如何使用javascript中的最新添加值更新数组中的重复值

时间:2014-02-03 13:22:39

标签: javascript arrays

我正在使用javascript,我有一个数组,我想用用户输入的最新值替换重复的值。用户输入DataName和数据的值。 例如,用户输入:

                             data.put value_a 50
                             data.put value_b 100
                             data.put value_a 200
                             data.put value_c 150

那就是什么打印输出:

                             value_a 200
                             value_b 100
                             value_c 150

正如您所看到的,value_a获取200的值,这是最新的附加值,因此50被200替换。

这就是我尝试创建数组并显示数据,但它不会删除重复数据。

 var formatedData = [];
                    _.each(this.EnteredData, function(inputLine) {
                        if(inputLine.indexOf("data.set") !== -1){
                            var args = inputLine.split(" ");
                            if(args[0] === "data.set"){
                                if(!_.isUndefined(args[1]) && !_.isUndefined(args[2])){
                                        if(args[1].length !== 0 && args[2].length !== 0){
                                            var dataObj = {
                                            name : args[1],
                                            value : args[2]
                                            };
                                            formatedData.push(dataObj);
                                        }
                                }

//显示数组

if(formatedData.length !== 0) {
                        $('#terminal').html(" Entered values are:\r\n");
                        _.each(formatedData, function(data) {
                            $('#terminal').append(data.name + " : " + data.value + "\r\n");
                        });
                        this.validatedData = formatedData.slice(0);
                        this.toggleSaveButton();
                    }

上面的代码显示了所有输入的值(包括重复的值),但我不知道如何使用最新添加的元素更新重复的值。也许我需要关联或哈希来替换它们?

任何提示?

由于

2 个答案:

答案 0 :(得分:0)

您可以使用push添加,print更简单地写入值:

如果您需要使用新值替换旧值,则可以使用此函数将o变量上的键定义为property,并在获得相同的键时添加值{{ 1}}引用o[key]上的现有属性,并且旧值自动更改为新值:

o

如果您也需要旧值,则可以使用此函数将var o = {}; function push(key, value) { o[key] = value; }; function print() { for (var i in o) console.log("key: " + i + ", value: " + o[i]); }; 定义为数组,并保留旧值和新值:

o

您也可以通过var o = []; function push(key, value) { o.push({ key: key, value: value }); }; function print() { for (var i = 0; i < o.length; i++) { console.log("key: " + o[i].key + ", value: " + o[i].value); } }; 实施print,这是由新浏览器提供的(您可以按照forEach主题获取更多示例和解释......):

LINQ to JavaScript

答案 1 :(得分:0)

根据我们所有的讨论,帖子和评论, 如果我是你,对于输入数据,并验证它是否有效格式,我正在创建代理或管理器,我没有混合验证,推送和获取数据到其他代码, 你甚至可以使用这个代码的小块作为库,并将所有这些保存到js中,并在你想要的每个页面中使用它... 这种编码有如此优势 最后,如果我想写这个脚本,我写的是这样的:

<script>

    +function () {

        //----------------------------------------------- linq extensions (these functions is added for older browsers)
        // if you need to learn what linq is, you can follow some documentations

        Array.prototype.forEach =
            Array.prototype.forEach ?
            Array.prototype.forEach :
            function (handler) {

                if (handler && typeof handler == "function") {
                    for (i = 0; i < this.length; i++)
                        handler(this[i]);
                }
        };

        Array.prototype.every =
            Array.prototype.every ?
            Array.prototype.every :
            function (handler) {

                var isValid = true;
                this.forEach(function (u) {

                    var result = handler(u);
                    isValid = isValid && result;
                });
                return isValid;
        };
        //----------------------------------------------- end linq extensions



        oProxy = new Proxy();                       // this is a manager that other has access only to this, and send request to this manager
        function Proxy() {                          // proxy class

            //------------ private members
            this.__o = {};                          // repository for data, as a dictionary
            //------------ end private members


            //------------ instance members
            this.Reset = function () {              // to reset proxy

                this.__o = {};
            };

            // your input is a string, that each part separate by a space
            // i called first part as type
            // second part as key
            // and third part as value
            this.Push = function (requestString) {  // add a value to dictionary, if it is valid

                var oProxyRequest = ProxyRequest.CreateRequest(requestString);
                if (oProxyRequest != null) {

                    var typeObject = this.__o[oProxyRequest.Type] || {};
                    typeObject[oProxyRequest.Key] = oProxyRequest.Value
                    this.__o[oProxyRequest.Type] = typeObject;

                    return oProxyRequest;
                }

                return null;
            };

            this.GetValues = function () {          // populate an array from dictionary, and return it, 
                                                    // every item on array has three property
                                                    // 1: Type
                                                    // 2: Key
                                                    // 3: Value

                var o = [];
                for (i in this.__o) {

                    var type = i;
                    var keyValuePairList = this.__o[i];
                    for (t in keyValuePairList) {

                        var key = t;
                        var value = keyValuePairList[key];

                        o.push(new ProxyRequest(key, value, type));
                    }
                }

                return o;
            };

            this.Print = function () {              // write items to console

                this.GetValues().forEach(function (u) {

                    console.log("Type: " + u.Type + ", Key: " + u.Key + ", Value: " + u.Value);
                });
            };
            //------------ instance members



            //----------------------------------------------- inner class
            function ProxyRequest(key, value, type) {

                this.Key = key;
                this.Value = value;
                this.Type = type;
            };                  // used to map string value to a type


            //------------ static members
            ProxyRequest.CreateRequest = function (requestString) {     // map input string to a ProxyRequest if input string was valid

                if (isValid(requestString)) {

                    var args = requestString.split(" ");
                    return new ProxyRequest(args[1], args[2], args[0]);
                }

                return null;
            };
            //------------ end static members


            //------------ private members
            function isValid(requestString) {                           // implementaion to validate input string

                if (requestString == null ||
                    requestString == undefined ||
                    requestString == "")
                    return false;


                if (requestString.indexOf("data.set") !== -1) {         // if you bypass this condition you can apply grouping
                                                                        // on keys, like this: every old key on its group replace by new key on that group
                                                                        // for example: 
                                                                        // you can add these two :
                                                                        // 1: "data.set value_a 100"
                                                                        // 2: "data.put value_a 200"
                                                                        // now you have two group and two key with values 100 and 200
                                                                        // but if you add this: "data.set value_a 500"
                                                                        // now you have "data.set value_a 500" and "data.put value_a 200"
                                                                        // but, by current implementation which you have
                                                                        // you can just add "data.set" as type
                                                                        // and all "keys" must be unique at this group
                                                                        // and by this explanation, if you add this twoL
                                                                        // 1: "data.set value_a 100"
                                                                        // 2: "data.set value_a 200"
                                                                        // you just have latest input "data.set value_a 200"


                    var args = requestString.split(" ");
                    if (args.every(function (u) { return u.length !== 0; }) &&
                        args[0] === "data.set") {

                        return true;
                    }
                }

                return false;
            };
            //------------ end private functions
            //----------------------------------------------- end inner class
        };

    }();

</script>

您可以通过以下语句将此封装代理与其他代码一起使用:

oProxy.Push("data.set value_a 100");
oProxy.Push("data.set value_b 200");
oProxy.Push("data.set value_a 300");

oProxy.Print();

oProxy.GetValues();

oProxy.Reset();
oProxy.Print();

您可能认为此代理类具有太多代码,但它具有非常优势