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

如何使用javascript中的最新添加值更新数组中的重复值,javascript,arrays,Javascript,Arrays,我正在使用javascript,我有一个数组,我想用用户最新输入的值替换重复的值。用户输入数据名和数据的值。 例如,用户输入: data.put value_a 50 data.put value_b 100 data.put value_a 200 data.put

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

                             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();
                    }
上面的代码显示了所有输入的值(包括重复的值),但我不知道如何用最新添加的元素更新重复的值。也许我需要关联或散列来替换它们

有什么提示吗


谢谢

您可以使用
推送
来添加,使用
打印
来编写更简单的值:

如果需要将旧值替换为新值,可以使用此函数,您的键在
o
变量上定义为
属性
,当您获得相同的键来添加值
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);
    }
};

根据我们所有的讨论、帖子和评论, 如果我是你,为了输入数据,验证其格式是否有效,我创建了一个代理或管理器,我没有混合验证,将数据推送到其他代码中, 您甚至可以将这段代码作为库使用,并将其保存到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>

您可能认为这个代理类的代码行太多,但它有很大的优势

您的代码出了什么问题。。。你看到错误了吗。。。期望的结果是什么?代码是正确的,我不知道如何用最新的附加值替换重复的。所以请先尝试。。。试试看。。。如果你失败了,你会向他们寻求帮助。谢谢,我的代码工作正常,显示了所有输入的值(包括重复的值),但我不知道如何用最新添加的元素更新重复的值。你的代码太痛苦了,你可以很简单地实现你想要的,就像我上面说的谢谢,但是您的代码是否用新添加的值更新重复的值?它是如何寻找重复项的?是的,你这么说了,在你的问题中
我想用用户最新输入的值替换重复的值
我编辑了这篇文章,以返回重复项的新旧值w!谢谢,看起来太复杂了!我不知道如何使用它,它是用javascript编写的吗有可能在JSFIDLE中完成吗?我真的很难理解!你给巴拉姆发电子邮件了吗?Merci编写了如何使用这个代理,您只需在js中添加我的第一个包含实现的脚本,然后简单地使用,正如我所说:要推送,只需调用:
oProxy.push(“data.set value_a 100”)
,要获取,只需调用:
oProxy.GetValues(),要重置:
oProxy.reset(),并写入控制台:
oProxy.Print()
,如果我的帖子对你有用,请投他们一票,如果它们是你的答案,请将它们作为答案检查,为他人提供帮助,我的电子邮件是,我在yahoo中的显示名称
<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();