物品之间的空间

时间:2016-11-03 23:20:04

标签: javascript

在我的职业生涯中,我多次遇到过这个问题,从未考虑过这个问题。我的标准已经提升到我想要更好的解决方案的程度。我将使用ES6进行演示,但不需要限制同一语言的答案。这是问题所在:

给出一个单词列表,每个单词都是有条件打印的,但每个单词之间应该打印一个分隔符(即除了第一个单词之外的所有单词)。

我经常遇到if语句的长链这样的问题,如下所示:

let something_printed = false;
if (condition1) {
   print(word1); // no space needed here
   something_printed = true;
}
if (condition2) {
   if (something_printed)
      print(' '); // but now a space is necessary
   print(word2);
   something_printed = true;
}
if (condition3) {
   if (something_printed)
      print(' '); // here too
   print(word3);
   something_printed = true;
}

或循环:

let something_printed = false;
for (let [word, condition] of word_conditions) {
   if (condition)
      if (something_printed)
         print(' ');
   print(word);
   something_printed = true;
}

额外的条件,只是为了打印分隔符,让我无所适从。所以我想出了以下内容(可以适应上述任何一个例子):

let separator = ''; // separator is initially empty
for (let [word, condition] of word_conditions)
   if (condition) {
      print(separator + word);
      separator = ' '; // separator is a space here on out
   }

这是我提出的最简洁的解决方案,也是我一直在做的......很长一段时间。

所以这里我们有两个循环,第一个循环捕获第一个打印的单词,第二个循环处理所有前面的单词:

let words = word_conditions.keys();
let conditions = word_conditions.values();
let index;
for (index = 0; index < words.length; index++)
   if (conditions[index]) {
      print(words[index]);
      break;
   }
for (; index < words.length; index++)
   if (conditions[index])
      print(' ' + words[index]);

忽略额外的索引,第二个循环没有浪费,这很好,但这是一个更详细的解决方案,并且需要花费精力忽略额外的索引。

两次通过的方法似乎可能提供一些希望,并且非常好,但不是最简洁的,并且由于为打印的单词构建数组而花费时间和内存的代价:

let unconditional_words = [];
for (let [word, condition] of word_conditions)
   if (condition)
      unconditional_words.push(word);
print(unconditional_words.pop());
for (let word of unconditional_words)
   print(' ' + word);

当然,这是在狡辩,但我一直都遇到这种情况。那里必须有一个简洁而有效的实施方案。我没有探索更实用的方法,但感觉它可能包含几个比我上面所示更好的解决方案。

后记

我可能不应该使用Javascript作为我的例子,因为我想到的平台实际上没有空间来构建数组并执行连接。 (想想旧的微控制器。)但是,我所做的绝大部分工作并不局限于此。在我无法腾出空间的地方,我会坚持上面的第三个实现。在现代科技方面,join()适用,简洁,高效。像往常一样,利用别人的辛勤工作是最好的方法。谢谢Shadow。

所以我的ifs的第一个例子可以像这样使用join():

let words = [];
if (condition1)
   words.push(word1);
if (condition2)
   words.push(word2);
if (condition3)
   words.push(word3);
print(words.join(' '));

对于循环的第二个例子:

let words = [];
for (let [word, condition] of word_conditions)
   if (condition)
      words.push(word);
print(words.join(' '));

这为我提供了简单,简单且易于理解的解决方案。好的。

2 个答案:

答案 0 :(得分:1)

听起来你正在寻找join功能。 在javascript(和ES6)

["First item", "Second item"].join(", ");

将返回

"First item, Second item"

答案 1 :(得分:0)

使用join是在JavaScript中执行此操作的内置方法。

var words = "Hello this is my sentence";
var comma = words.split(" ").join(", ");
console.log(comma);

相关问题