简体   繁体   English

未定义的变量? 加密/解密

[英]Undefined variable? encrypt/decrypt

Hey i am trying to make a simple encrypt/decrypt javascript.嘿,我正在尝试制作一个简单的加密/解密 javascript。 I am having a lot of trouble using variables from my first function into the second function.我在使用第一个函数中的变量到第二个函数时遇到了很多麻烦。

the first function encrypts第一个函数加密

2nd function decrypts第二个函数解密

problem: I cannot use the variables I used in my first function.问题:我不能使用我在第一个函数中使用的变量。 For example for "encoded" it keeps returning undefined!例如对于“编码”,它一直返回未定义! I attached my short code under.我在下面附上了我的短代码。

 var encoded; function code(string, pass) { array=[] for (var i = 0; i<string.length; i++) { //converts code into an array & unicode b = (string.charCodeAt(i)) array.push(b) } //encovder let encoded = array.map(function(x) { return x*pass }) return encoded } (code("hello",7)) //decode function decoded() { console.log(encoded) } console.log(decoded())

You should assign the value of the function to your variable in the relevant scope:您应该将函数的值分配给相关范围内的变量:

var encoded;
function code(string, pass){
array=[]
for (var i = 0; i<string.length; i++){
//converts code into an array & unicode
b = (string.charCodeAt(i))
array.push(b)
}
//encovder
let encoded = array.map(function(x){
  return x*pass
})
return encoded
}
encoded = (code("hello",7));

By the way your result will be NaN because "hello".charCodeAt(5) is NaN and NaN * number == NaN .顺便说一下,你的结果将是NaN因为"hello".charCodeAt(5)NaNNaN * number == NaN

Because you don't set the variable encoded that is defined on the first line, thus it value will be undefined when you try to log it.因为您没有设置在第一行定义的变量encoded ,因此当您尝试记录它时,它的值将是undefined

WHY?为什么?

because inside code you redefine encoded on this line let encoded = ... and the later one shadows the one defined on the first line.因为在此行上重新定义encoded内部code let encoded = ...并且后面的代码遮蔽了第一行定义的代码。 So, here the second one gets set and not the first one (global one).因此,这里设置了第二个而不是第一个(全局一个)。

How to solve this?如何解决这个问题?

You either not declare a new encoded inside the function (so this let encoded = ... should become this encoded = ... . Or assign the returned value of code to the global encoded like this var encoded = code("hello", 7); .你要么没有在函数内部声明一个新的encoded (所以这let encoded = ...应该变成这个encoded = ... 。或者将code的返回值分配给全局encodedvar encoded = code("hello", 7);

An example of Variable Shadowing :变量阴影的一个例子

 var value = 5; console.log(value); // uses the above value function foo(){ var value = 99; // redefining value (shadowing occur from this point) console.log(value); // logs the newly defined value. }// at this point, the value (99) gets destroyed. foo(); console.log(value); // logs 5 as it is the one belonging to this scope no matter wether the value (99) gets destroyed or not.

Read more about Scopes and Variable shadowing and Variables lifetime .阅读有关范围变量阴影以及变量生命周期的更多信息。

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

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