我试图加密用户输入的单词,但它只加密该单词的最后一个字母。
换句话说,如果我输入abc
并单击按钮,浏览器将显示z
而不是xyz
。它忽略了ab
的加密。
我做错了什么&我如何才能纠正这个错误?
import React, { Component } from 'react';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
show: false,
encryptedValue: null
};
}
encrypt = () => {
let input = document.getElementById("inputText").value;
let encryptedValue;
let temp = "";
for(let i = 0; i < input.length; i++) {
temp += input[i];
switch(input[i].charAt(i)) {
case "a":
encryptedValue = "x";
break;
case "b":
encryptedValue = "y";
break;
case "c":
encryptedValue = "z";
break;
default:
encryptedValue = null;
}
}
document.getElementById("res").innerHTML = temp;
this.setState({show: true, encryptedValue: encryptedValue});
};
render() {
return(
<div>
<input type="text" placeholder="type something" id="inputText"/>
<button onClick={() => this.encrypt()}>Click to encrypt</button>
<h1 id="res">{this.state.encryptedValue}</h1>
</div>
);
}
}
export default Main;
发布于 2018-10-24 03:25:25
在每种情况下都将字符串设置为新值,而不是向其追加字符。对于初学者,您可以尝试+=而不是= This将适用于abc,但如果您输入obc,您将只得到yz。
要使其适用于所有情况,请先将原始字符串复制到encryptedValue中,然后在每种情况下将encryptedValuei设置为加密字符
发布于 2018-10-24 03:30:58
如果您试图使"encryptedValue“成为加密字符串,则应该连接到它,因此它应该是
encryptedValue=encryptedValue+"x";
或更短的版本
encryptedValue+="x";
你也可以在react https://www.npmjs.com/package/react-encrypt中使用加密导入,它有像"encrypt(string)“这样的简单功能。
https://stackoverflow.com/questions/52956437
复制相似问题