2011-05-14 74 views
0

對於這個非常新手的問題,我很抱歉,但這讓我很生氣。從並行數組中返回一個字符串

我有一個詞。對於單詞的每個字母,找到一個數組中的字符位置,然後將該字符返回到並行數組(基本密碼)中找到的相同位置。這是我已經有:

*array 1 is the array to search through* 
*array 2 is the array to match the index positions* 

var character 
var position 
var newWord 

for(var position=0; position < array1.length; position = position +1) 
{ 
    character = array1.charAt(count);  *finds each characters positions* 
    position= array1.indexOf(character); *index position of each character from the 1st array* 
    newWord = array2[position];   *returns matching characters from 2nd array* 
} 

document.write(othertext + newWord);  *returns new string* 

我的問題是,在目前的功能只寫出來的新詞的最後一個字母。我希望在document.write中添加更多的文本,但是如果我放在for循環中,它會寫出新的單詞,但也會寫出每個單詞之間的其他文本。我真正想要做的是返回othertext + newWord而不是document.write,以便稍後使用它。 (只是使用doc.write文本我的代碼):-)

我知道它的東西很簡單,但我不知道我哪裏去錯了。有什麼建議? 由於 伊西

+0

嗨伊西,歡迎來到SO。不幸的是,如果大多數用戶對「家庭作業」風格的問題有些嗤之以鼻,他們很可能不會迴應。此外,這是什麼語言? – Ben 2011-05-14 08:31:08

+0

史蒂夫,謝謝你的回覆,是的,我知道它很難,我真的想爲自己工作,但我只是需要一個正確的方向,因爲我完全卡在哪裏去。它在JavaScript中。謝謝Issy – user753420 2011-05-14 08:50:58

回答

0

構建代碼和問題的一種好方法是定義需要實現的function。你的情況,這可能是這樣的:

function transcode(sourceAlphabet, destinationAlphabet, s) { 
    var newWord = ""; 

    // TODO: write some code 

    return newWord; 
} 

這樣,你清楚地說明你想要什麼,哪些參數都參與其中。以後編寫自動測試也很容易,例如:

function testTranscode(sourceAlphabet, destinationAlphabet, s, expected) { 
    var actual = transcode(sourceAlphabet, destinationAlphabet, s); 
    if (actual !== expected) { 
    document.writeln('<p class="error">FAIL: expected "' + expected + '", got "' + actual + '".</p>'); 
    } else { 
    document.writeln('<p class="ok">OK: "' + actual + '".'); 
    } 
} 

function test() { 
    testTranscode('abcdefgh', 'defghabc', 'ace', 'dfh'); 
} 

test(); 
+0

感謝這是偉大的:-)問題是,我沒有initalise新的詞 - 現在我可以正確地測試它。 Issy :-) – user753420 2011-05-14 12:44:27

1

的解決方案是使用+=代替=環內建立newWord。在循環之前將其設置爲空字符串。

此代碼還有其他問題。變量count從不初始化。但讓我們假設循環應該使用count而不是position作爲它的主要計數器。在這種情況下,如果我沒有弄錯,這個循環將會產生array2作爲newWord。前兩行循環的主體在發言時會相互抵消,並且position將始終等於count,因此從array2開始的字母將從頭到尾依次使用。

您能否提供一個輸入和期望輸出的例子,以便我們理解您真正想要完成的任務?

+0

嗨對不起,它應該算數而不是位置。我有兩個數組,一個是'a,b,c,d,e,f,g,h,另一個是'd,e,f,g,h,a,b,c',我的單詞可能是'ace' 。這個單詞將查找第一個數組以獲得它們的索引編號,然後它將使用這些索引編號查看第二個數組並返回字符串'deh'。上面的例子(當我使用正確的循環詞;-))寫出了字符串,但僅僅是因爲它在循環內 - 我需要把它寫出 - 在循環之外。我有沒有道理?請原諒我的散漫 – user753420 2011-05-14 09:26:32

+0

返回的字符串不應該是'dfh'嗎?另外,代碼中沒有提及輸入字符串。我想循環體的第一行應該有'oldWord'而不是'array1'。就像我說的,解決方法是在第三行使用+ =而不是=。 – Dialecticus 2011-05-14 09:34:37