2016-08-30 29 views
3

我試圖建立一個簡單的「密碼」來分配字符串中的字母倒序字母表的值(例如a = zb = y等..)我建立了一個for語句,似乎工作,直到最後一次調用,而不是給予反向值,而是給出原始值。對於語句返回上一次作業的意外值

我在for語句的每一行註釋掉了,然後逐個查看它們的返回值。倒數第二個語句(c = rev.indexOf(c);)給出了25,24,23的值(與預期的一樣),所以我不明白爲什麼當它在「字母」矩陣中查找它時,會給出返回a,b,c而不是z,y,x。

var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'y', 'x', 'z']; 
var rev = letters.reverse(); 

var stringy = function(n){ 
    ns = n.split(""); 
    for (i = 0; i < n.length; i++){ 
      c = ns[i]; 
      c = rev.indexOf(c); 
      c = letters[c]; 
      console.log(c); 
    } 
} 

stringy("abc"); 
+2

@chchrist是什麼這與閉包有關,還是與循環有關? – 2016-08-30 17:17:15

回答

4

letters.reverse()不只是返回顛倒的數組。它顛倒了陣列。

如果您在letters.reverse()之後檢查letters的內容,您會看到訂單已被調換。

您可以使用.slice()使數組,然後你就可以扭轉的副本:

var rev = letters.slice().reverse(); 
+0

完美,謝謝!我沒有意識到.reverse這樣表現。 – oneWorkingHeadphone

+0

@oneWorkingHeadphone,'sort'也可以,我不喜歡這種行爲。 – zzzzBov

1

作爲除zzzzBov信息到Array.reverse()方法,我以爲我想補充一點,沒有按」答案要求反轉你的信件。沒有必要保留2個變量只是爲了根據索引來反轉它們,只需在letters數組中找到索引並從letters數組末尾搜索。

我加入你的代碼稍加修改的版本,向您展示如何使自己更容易一點,並添加一些代碼註釋,我認爲適當

// make your debugging easier 
 
'use strict'; 
 

 
var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'y', 'x', 'z']; 
 

 
var getReversedCypher = function(text, sequence, unmatched) { 
 
    if (!text) { 
 
    return ''; 
 
    } 
 
    var ns = text.split(''), 
 
     cypher = [], 
 
     lastLetterIndex = sequence.length - 1; 
 
    
 
    // use strict adds forEach on arrays 
 
    ns.forEach(function(char) { 
 
    var index = sequence.indexOf(char); 
 
    if (index < 0) { 
 
     // couldn't find a match, you could throw an error, I chose to add an extra character 
 
     cypher.push(unmatched || '-'); 
 
    } else { 
 
     // no need to use a reversed lookup, just search the table from the end 
 
     cypher.push(sequence[lastLetterIndex-index]); 
 
    } 
 
    }); 
 
    return cypher.join(''); 
 
}; 
 

 
// make some utility methods to still use your simple function 
 
var encode = function(text) { 
 
    return getReversedCypher(text, letters, '-'); 
 
}; 
 

 
var decode = function(text) { 
 
    return getReversedCypher(text, [].concat(letters).reverse(), ' '); 
 
}; 
 
    
 
var encoded = encode("this is the sound of speech"), decoded = decode(encoded); 
 

 
console.log('cypher: ' + encoded); 
 
console.log('decoded: ' + decoded);

+0

這就像你正在閱讀我的想法:)這是我正在接下來的工作。非常感謝你的回答,我可以從這個工作中學到很多東西。 – oneWorkingHeadphone