简体   繁体   English

为什么首先考虑上述else语句而不是上面的if值之一?

[英]Why is this else statement being considered first than one of the if values above?

This function loops through an array of strings. 此函数遍历字符串数组。 If the string doesn't start with an # it's wrapped with a p tag. 如果字符串不是以#开头,则使用p标签进行包装。 If the previous string of the string is a # or a * * * it's wrapped with a p tag with the class ni 如果字符串的前一个字符串是#* * *则将其包装为带有ni类的p标签

function replaceParagraphs(data) {
  data = data.split('\n\n')
  for (var i = 0; i < data.length; ++i) {
    if (data[i].match(/^[^#]/g)) {
      var content = data[i].replace(/\n(?=\w)/g, ' ').replace(/\n(?=$)/g, '')
      if (data[i - 1].match(/^#/g) || data[i - 1] === "* * *") {
        data[i] = '<p class="ni">' + content + '</p>'
      } else {
        data[i] = '<p>' + content + '</p>'
      }
    }
  }
  data = data.join('\n\n')

  return data
}

But it seems like data[i - 1] === "* * *" is not being considered, since I end up with an output like this: 但是似乎没有考虑data[i - 1] === "* * *" ,因为我最终得到这样的输出:

## Test

<p class="ni">Lorem “ipsum?” dolor ‘sit!’ amet</p>

<p>Consetetur eirmod</p>

<p>* * *</p>

<p>“Ipsum?” “‘dolor’” sit! amet, consetetur eirmod tempor—invidunt ut labore</p>

What could be the problem? 可能是什么问题呢?

EDIT: 编辑:

Oh, based on the answers and comments I realized that it's because the code produces <p>* * *</p> 哦,根据答案和评论,我意识到这是因为代码产生了<p>* * *</p>

What can I do to prevent this? 我该怎么做才能避免这种情况?

Because you replaced * * * with <p>* * *</p> in the previous step. 因为您在上一步中用<p>* * *</p>替换了* * *

That conditional data[i - 1].match(/^#/g) || data[i - 1] === "* * *" 该条件data[i - 1].match(/^#/g) || data[i - 1] === "* * *" data[i - 1].match(/^#/g) || data[i - 1] === "* * *" can only ever possibly be true on the first iteration. data[i - 1].match(/^#/g) || data[i - 1] === "* * *"只能在第一次迭代中为true。

Consider writing into a fresh array, for clarity and to resolve issues like this. 为清楚起见并考虑解决此类问题,请考虑将其写入新数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM