0

非常に初心者の質問で申し訳ありませんが、これは私を怒らせています。

一言あります。単語の文字ごとに、1つの配列内の文字位置が検出され、並列配列内の同じ位置にある文字が返されます(基本暗号)。これは私がすでに持っているものです:

*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ループ内に配置すると、新しい単語だけでなく、各単語の間にある他のテキストも書き出されます。私が実際にやりたいのは、後で使用できるように、document.writeではなくothertext+newWordを返すことです。(doc.writeを使用してコードにテキストを送信するだけです):-)

私はそれが本当に単純なことを知っていますが、どこが間違っているのかわかりません。何かアドバイス?ありがとうIssy

4

2 に答える 2

1

解決策は、代わりに をnewWord使用してループ内に構築することです。ループの前に空の文字列に設定するだけです。+==

このコードには他にも問題があります。変数countは初期化されません。しかし、ループがプリンシパル カウンターのcount代わりに使用する必要があると仮定しましょう。positionその場合、私が間違っていなければ、このループは として生成さarray2newWordます。ループの本体の最初の 2 行は話し方で互いに打ち消し合い、position常に と等しいためcount、 の文字array2が最初から最後まで順番に使用されます。

実際に達成したいことを理解できるように、インプットと望ましいアウトプットの例を 1 つ挙げていただけますか?

于 2011-05-14T09:20:28.383 に答える
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();
于 2011-05-14T09:56:59.707 に答える