NodeJS v8.12.0-x64 ДЛЯ LOOP неожиданные результаты - PullRequest
0 голосов
/ 09 ноября 2018

Является ли "i" зарезервированной переменной? Может показаться маловероятным вопросом. Однако, когда я запускаю следующий простой код на моем компьютере, и переменная итерации, используемая в цикле FOR, устанавливается как "i" , после первого выполнения цикла "i" возвращается как 63 .

Когда "i" изменяется на z, omega или какую-либо другую переменную name, цикл работает должным образом. Я что-то пропустил? Это проблема с моим компьютером?

/*
This javascript code demonstrates a simple encode/decode of a string using a hash of possible values
    stored in a JSON object.
*/

objPossibleCharacters = {
    "Z" : "c",          "Y" : "i",          "X" : "P",          "W" : "O",
    "V" : "b",          "U" : "5",          "T" : "V",          "S" : "a",
    "R" : "4",          "Q" : "Z",          "P" : "U",          "O" : "h",
    "N" : "d",          "M" : "R",          "L" : "3",          "K" : "N",
    "J" : "E",          "I" : "w",          "H" : "D",          "G" : "2",
    "F" : "e",          "E" : "v",          "D" : "q",          "C" : "j",
    "B" : "Q",          "A" : "1",          "0" : "G",          "1" : "f",
    "2" : "C",          "3" : "F",          "4" : "o",          "5" : "M",
    "6" : "0",          "7" : "r",          "8" : "L",          "9" : "H",
    "a" : "g",          "b" : "6",          "c" : "s",          "d" : "m",
    "e" : "S",          "f" : "7",          "g" : "x",          "h" : "p",
    "i" : "X",          "j" : "B",          "k" : "8",          "l" : "I",
    "m" : "y",          "n" : "T",          "o" : "k",          "p" : "J",
    "q" : "W",          "r" : "z",          "s" : "K",          "t" : "l",
    "u" : "t",          "v" : "9",          "w" : "A",          "x" : "Y",
    "y" : "u",          "z" : "n",          "!" : "%",          "?" : "~",
    "," : "*",          "." : "$",          " " : "|"
};

function encodeString( str ){
    encodedStr = "";
    for (i=0; i < str.length; i++){
        encodedStr += objPossibleCharacters[str.charAt(i)];
    }
    //console.log( encodedStr );
    return encodedStr;
}

function decodedString( str ){
    decodedStr = "";
    value = "";
    for ( i=0; i < str.length; i++ ){
        value = str.charAt(i);
        decodedStr += getKeyByValue( value );
    }
    //console.log( decodedStr );
    return decodedStr;
}

function getKeyByValue( value ){
    for ( key in objPossibleCharacters ){
        if ( objPossibleCharacters.hasOwnProperty( key ) ){

            if ( objPossibleCharacters[key] === value ) return key;
        }
    }
}

var strArray = [ 
    'Sea shells, sea shells.  She sells sea shells by the sea shore.', 
    'Thank you for coming today.  I hope you found this session enlightening and useful.', 
    'Elvis has left the building.  You do not need to go home, but you cannot stay here.  Get out!' ];

strArrayLength = strArray.length;

// This issue is in the following FOR LOOP
// Change var x = 0 to var i = 0
var x = 0;
for (x=0; x<strArrayLength; ++x){

        str = strArray[x];
        encodedOutput = encodeString( str );
        decodedOutput = decodedString( encodedOutput );

        console.log( "" );
        console.log( "Original string: " +str );
        console.log( "Encoded string: " +encodedOutput );
        console.log( "Decoded string: " +decodedOutput );
        console.log( strArrayLength +" - "+ x );
        console.log( "" );
}

Когда i используется в качестве переменной, я получаю только следующий вывод:

Original string: Sea shells, sea shells.  She sells sea shells by the sea shore.
Encoded string: aSg|KpSIIK*|KSg|KpSIIK$||apS|KSIIK|KSg|KpSIIK|6u|lpS|KSg|KpkzS$
Decoded string: Sea shells, sea shells.  She sells sea shells by the sea shore.
3 - 63

Когда используется другое имя переменной, я получаю следующий вывод:

Original string: Sea shells, sea shells.  She sells sea shells by the sea shore.
Encoded string: aSg|KpSIIK*|KSg|KpSIIK$||apS|KSIIK|KSg|KpSIIK|6u|lpS|KSg|KpkzS$
Decoded string: Sea shells, sea shells.  She sells sea shells by the sea shore.
3 - 0


Original string: Thank you for coming today.  I hope you found this session enlightening and useful.
Encoded string: VpgT8|ukt|7kz|skyXTx|lkmgu$||w|pkJS|ukt|7ktTm|lpXK|KSKKXkT|STIXxplSTXTx|gTm|tKS7tI$
Decoded string: Thank you for coming today.  I hope you found this session enlightening and useful.
3 - 1


Original string: Elvis has left the building.  You do not need to go home, but you cannot stay here.  Get out!
Encoded string: vI9XK|pgK|IS7l|lpS|6tXImXTx$||ikt|mk|Tkl|TSSm|lk|xk|pkyS*|6tl|ukt|sgTTkl|Klgu|pSzS$||2Sl|ktl%
Decoded string: Elvis has left the building.  You do not need to go home, but you cannot stay here.  Get out!
3 - 2

1 Ответ

0 голосов
/ 09 ноября 2018

Все ваши функции неправильно объявляют переменную i. Поскольку var i = 0 получает hoisted , эта переменная будет использоваться всеми вашими функциями.

Например:

function encodeString( str ){
  encodedStr = "";
  for (i=0; i < str.length; i++){ ... }
}

Правильная декларация:

function encodeString( str ){
  let encodedStr = "";
  for (let i=0; i < str.length; i++){ ... }
}

То же самое относится и к другим переменным, которые вы используете.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...