简体   繁体   English

查找等于值的键不起作用

[英]Finding keys equal to values not working

Alright, so I was sitting around one day thinking about "What if I make my own encoding like Base64 in JavaScript?" 好吧,所以我整天闲逛着,想着“如果我像JavaScript中使用Base64那样编写自己的编码该怎么办?” and then I came up with the idea of creating a library that allows you to make your own encoding like Base64. 然后我想到了创建一个库的想法,该库允许您进行自己的编码,例如Base64。 This is the code I came up with: 这是我想出的代码:

var Zinc = Zinc || {};
Zinc.Encoding = function(name) {
    this.encodingName = name;
    this.conversionTable = {};
    this.addToTable = function(string, convertsTo) {
        this.conversionTable[string] = convertsTo;
    };
    this.removeFromTable = function(string) {
        delete this.conversionTable[string];
    };
    this.encode = function(string) {
        var len = string.length;
        var out = string.split("");
        for (var i = 0; i < out.length; i++) {
            out[i] = this.conversionTable[out[i]];
        }
        return out.join("");
    }
    this.decode = function(string) {
        var len = string.length;
        var dec = string.split("");
        var out = [];

        for (var i = 0; i < dec.length; i++) {
            out[i] = this.getTableKeyByValue(dec[i]);
        }

        return out.join("");
    }
    /* Used internally. */
    this.getTableKeyByValue = function(value) {
        for (var prop in this.conversionTable) {
            if (this.conversionTable.hasOwnProperty(prop)) {
                if (this[prop] === value)
                    return prop;
            }
        }
    };
}

window.Zinc = Zinc;

Encoding works and everything, just try this: 编码可以完成所有工作,只需尝试以下操作:

var test = new Zinc.Encoding(); test.addToTable("j", "blah"); test.encode("j");

And it outputs: "blah" . 它输出: "blah"

Try doing: test.decode("blah") , but it does not do anything, and returns "". 尝试做: test.decode("blah") ,但是它什么也不做,并返回“”。 Why does it do this instead of finding the key in the table object and getting the name that is equal to the value, and turn the value into the name that is equal to the value. 为什么这样做而不是在表对象中查找键并获得与值相等的名称,然后将值转换为与值相等的名称。 (confusing, right?) (令人困惑,对吧?)

Decode is breaking out each character of the string passed in. Maybe you mean to split on word boundaries instead: 解码会分解传入的字符串的每个字符。也许您的意思是拆分单词边界:

 var conversionTable = { 'j': 'blah' }; function decode(string) { var len = string.length; var dec = string.split(/\\b/); var out = []; for (var i = 0; i < dec.length; i++) { out[i] = this.getTableKeyByValue(dec[i]); } return out.join(" "); }; function getTableKeyByValue(value) { for (var prop in conversionTable) { if (conversionTable.hasOwnProperty(prop)) { if (conversionTable[prop] === value) return prop; } } }; console.log( decode('blah') ); console.log( decode('blah blah') ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM