项目之间的空间

Space between items

本文关键字:空间 之间 项目      更新时间:2023-09-26

在我的职业生涯中,我已经多次遇到这个问题,但从来没有仔细考虑过。我的标准已经提高到我想要一个更好的解决方案的程度。我将使用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()是适用的、简洁的和高效的。像往常一样,利用别人的辛勤工作是最好的方法。由于阴影。

那么我的第一个if的例子可以像这样使用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(' '));

它给了我简短,简单,易懂的解决方案。好。

听起来您正在寻找连接函数。javascript(和ES6)

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

将返回

"First item, Second item"

使用join是JavaScript内建的方法。

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