【问题标题】:Returning a string from a parallel array从并行数组中返回一个字符串
【发布时间】:2011-05-14 08:22:52
【问题描述】:

对于这个新手问题我很抱歉,但这让我发疯了。

我有话要说。对于单词的每个字母,找到一个数组中的字符位置,然后返回在并行数组中找到的相同位置的字符(基本密码)。这是我已经拥有的:

*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 给我的代码发短信):-)

我知道这很简单,但我看不出哪里出错了。有什么建议吗? 谢谢 伊西

【问题讨论】:

  • 嗨,Issy,欢迎来到 SO。不幸的是,如果大多数用户听到“家庭作业”式的问题,他们就不太可能做出回应。另外,这是什么语言的?
  • 嗨史蒂夫,谢谢你的回复,是的,我知道这很困难,我真的很想自己解决这个问题,但我只需要一个正确的方向,因为我完全坚持去哪儿。它在 JavaScript 中。谢谢伊西

标签: javascript string parallel-arrays


【解决方案1】:

解决方案是使用+= 而不是= 在循环内构建newWord。只需在循环之前将其设置为空字符串即可。

此代码还有其他问题。变量count 永远不会被初始化。但是让我们假设循环应该使用count 而不是position 作为它的主要计数器。在这种情况下,如果我没记错的话,这个循环只会将array2 生成为newWord。循环体的前两行可以说是相互抵消了,position永远等于count,所以array2中的字母会从头到尾依次使用。

您能否提供一个输入和期望输出的示例,以便我们了解您真正想要完成的任务?

【讨论】:

  • 嗨,是的,对不起,它应该是计数而不是位置。我有 2 个数组,一个是 'a,b,c,d,e,f,g,h,另一个是 'd,e,f,g,h,a,b,c' 我的话可能是 'ace' .这个词将在第一个数组中查找以获取它们的索引号,然后它将使用这些索引号来查找第二个数组并返回字符串 'deh' 。上面的例子(当我使用正确的循环词;-))确实写出了字符串,但只是因为它在循环内 - 我需要让它在循环外写出来。我说得有道理吗?请原谅我的漫无边际
  • 返回的字符串不应该是'dfh'吗?此外,您的代码中没有提及输入字符串。我想循环体的第一行应该有oldWord 而不是array1。就像我说的,解决方案是在第三行使用 += 而不是 =。
【解决方案2】:

一种构建代码的好方法,您的问题是定义一个需要实现的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();

【讨论】:

  • 谢谢,这太好了 :-) 问题是我没有初始化新 Word - 现在我可以正确测试它了。伊西:-)
猜你喜欢
  • 2012-08-21
  • 2011-09-04
  • 1970-01-01
  • 2013-03-17
  • 2015-08-05
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2013-04-18
相关资源
最近更新 更多