2017-03-06 92 views
0

为这个愚蠢的问题道歉。我正试图在Codewars上解决这个Kata,https://www.codewars.com/kata/the-enigma-machine-part-1-the-plugboard/train/javascript/。它基本上是一个Enigma机器的开始。我觉得我在这方面做了一些很好的进步。现在我通过pythontutor.com运行它,但是我不知道为什么当我运行这个时,for循环的第二次迭代将插件板的属性“A”更改为“C”,并且不是创建一个值为'A'的新属性'C'。我确信这是一个简单的概念,我完全错过了,但我肯定会对此有所了解。Javascript Object Key Value Confusion

class Plugboard { 

constructor(wires) { 

if(wires.length % 2 !== 0 || wires.length === 0 || wires.length > 20){ 
    throw 'Error' 
} 
    console.log(wires) 
    this.str = wires.split('') 

for(var i = 0; i < this.str.length; i += 2){ 
    if(this.hasOwnProperty(this.str[i])){ 
    throw 'Duplicate'; 
    } 
    this[this.str[i+1]] = this.str[i]; 
    this[this.str[i]] = this.str[i+1]; 

    } 
} 

process(chr){ 
    if(!this.hasOwnProperty(chr)){ 
     return chr 
    } else { 
     return this[chr]; 
     } 
    } 

} 
var plugboard = new Plugboard("ABCA"); 
+0

当我运行该代码时,我得到''B“:”A“,”A“:”C“,”C“:”A“这是不正确的还是我错过了什么? – JohanP

+0

引用你得到的实际输出和你期望得到的输出会好得多。 –

+0

再次,对不起!期望的输出是“B”:“A”; “A”:“B”; “C”:“A”; “A”:“C”;. 我希望实现的是为每对字符创建两个键值对。例如,如果input =('XY'),预期的输出this.X ='Y'; this.y ='X'。我知道有一些基本的东西我必须做错。 –

回答

0

C属性确实存在并且值为“A”。我跑它repl.it,它只是作品...

class Plugboard { 
 

 
constructor(wires) { 
 

 
if(wires.length % 2 !== 0 || wires.length === 0 || wires.length > 20){ 
 
    throw 'Error' 
 
} 
 
    console.log(wires) 
 
    this.str = wires.split('') 
 

 
for(var i = 0; i < this.str.length; i += 2){ 
 
    if(this.hasOwnProperty(this.str[i])){ 
 
    throw 'Duplicate'; 
 
    } 
 
    this[this.str[i+1]] = this.str[i]; 
 
    this[this.str[i]] = this.str[i+1]; 
 
    } 
 
} 
 

 
process(chr){ 
 
    if(!this.hasOwnProperty(chr)){ 
 
     return chr 
 
    } else { 
 
     return this[chr]; 
 
     } 
 
    } 
 

 
} 
 
var plugboard = new Plugboard("ABCA"); 
 
console.log(plugboard); 
 
console.log("Value of C:",plugboard.C); 
 
console.log("Value of A:",plugboard.A); 
 
console.log("Value of B:",plugboard.B);

repl.it链接:https://repl.it/GJg7/2

0

我猜你可能会得到措辞错误的这个问题,并且实际上担心A财产包含C值,而不是相反。

在第一循环中,我们作如下分配:

this["B"] = "A" 
this["A"] = "B" 

在第二循环中,我们作如下分配:

this["A"] = "C" 
this["C"] = "A" 

注意,这覆盖this["A"]现有的值。它不会被检测为重复项,因为我们只检查并且不检查this.str[i+1]是否重复。它不会添加重复的属性,因为我们不能拥有重复的属性。它完全按照它的要求去做。

如果这不是所需的行为,那么期望的行为是什么?

0

谢谢大家的意见。我意识到自己的错误,我在第二次传球时凌驾了C球。问题解决了,感谢和抱歉,我的无知