【问题标题】:How to simplify javascript program?如何简化javascript程序?
【发布时间】:2021-09-08 07:04:47
【问题描述】:

我希望最小化该程序。 也许将 p1-16 放在一行代码中,与 count 和 gefunden 相同? 由于我的语言能力很低,我找不到正确的信息。

如果有一种方法可以最小化搜索命中 pdf 中的 if else 语句,那就太好了。

现在我手动编写代码以添加新的 pdf,如搜索命中 pdf1 到 pdf2。任何更简单的方法都会对我有很大帮助。

function Suche(str){
    p1=document.getElementById('pdf1').innerHTML;
    p2=document.getElementById('pdf2').innerHTML;
    p3=document.getElementById('pdf3').innerHTML;
    p4=document.getElementById('pdf4').innerHTML;
    p5=document.getElementById('pdf5').innerHTML;
    p6=document.getElementById('pdf6').innerHTML;
    p7=document.getElementById('pdf7').innerHTML;
    p8=document.getElementById('pdf8').innerHTML;
    p9=document.getElementById('pdf9').innerHTML;
    p10=document.getElementById('pdf10').innerHTML;
    p11=document.getElementById('pdf11').innerHTML;
    p12=document.getElementById('pdf12').innerHTML;
    p13=document.getElementById('pdf13').innerHTML;
    p14=document.getElementById('pdf14').innerHTML;
    p15=document.getElementById('pdf15').innerHTML;
    p16=document.getElementById('pdf16').innerHTML;
    p17=document.getElementById('pdf17').innerHTML;
    gefunden1=0;
    gefunden2=0;
    gefunden3=0;
    gefunden4=0;
    gefunden5=0;
    gefunden6=0;
    gefunden7=0;
    gefunden8=0;
    gefunden9=0;
    gefunden10=0;
    gefunden11=0;
    gefunden12=0;
    gefunden13=0;
    gefunden14=0;
    gefunden15=0;
    gefunden16=0;
    gefunden17=0;
    count1=0;
    count2=0;
    count3=0;
    count4=0;
    count5=0;
    count6=0;
    count7=0;
    count8=0;
    count9=0;
    count10=0;
    count11=0;
    count12=0;
    count13=0;
    count14=0;
    count15=0;
    count16=0;
    count17=0;
    searchstring=str;
    
    
    //Search Hits PDF1
    
    endsearch=p1.length;
    weiter=1;
    
    
    if(p1.indexOf(str)>-1){
       gefunden1=1;
       pos1=p1.indexOf(str)+searchstring.length;
       count1=count1+1;}
    else{weiter=0;}
    
    for(i = 1; i <=10; i++){
       if(weiter==1){
          if(p1.indexOf(str,pos1)>-1){
             pos2=p1.indexOf(str,pos1)+searchstring.length;
             if (pos2<=endsearch){
                if(count1<10){
                   count1=count1+1;
                   pos1=pos2;}
                else{
                   count1="Mehr als 10";
                   pos1=pos2;}}
             else{
                weiter=0;}}
          else{
             weiter=0;}}}
    
    
    //Search Hits Pdf2
    
    
    endsearch=p2.length;
    weiter=1;
    
    if(p2.indexOf(str)>-1){
       gefunden2=1;
       pos1=p2.indexOf(str)+searchstring.length;
       count2=count2+1;}
    else{weiter=0;}
    
    
    for(i = 1; i <=10; i++){
       if(weiter==1){
          if(p2.indexOf(str,pos1)>-1){
             pos2=p2.indexOf(str,pos1)+searchstring.length;
             if (pos2<=endsearch){
                if(count1<10){
                   count2=count2+1;
                   pos1=pos2;}
                else{
                   count2="Mehr als 10";
                   pos1=pos2;}}
             else{
                weiter=0;}}
          else{
             weiter=0;}}}

等等……

【问题讨论】:

  • 我觉得这更适合codereview.stackexchange.com,因为你没有实际问题
  • 为什么不使用数组?
  • 使用数组并在其中存储具有countgefundenp 属性的对象。
  • 您只描述了您不喜欢当前解决方案的原因和方式。为了给你不同的观点,为什么不解释一下它实际上做了什么,或者应该做什么?
  • 这个问题和你之前问的For loop for repeatable action javasript?有什么不同?

标签: javascript


【解决方案1】:

为什么不使用名为 p 的数组?

const p = []
for (let i=1; i<18; i++) {
    p.push(document.getElementById(`pdf${i}`).innerHTML)
}

您可以对 gefunden 和 count 执行相同的操作。您的其余代码如果重复,可以进入一个函数并在另一个 for 循环中调用。

【讨论】:

    【解决方案2】:

    我同意这应该在代码审查中。但是你有一个工作代码,并询问如何使它变得更好。所以你去吧。

    • 用数组替换所有具有variableN 格式的变量。一旦有了这样的命名格式,大多数时候你要么想使用数组,要么更改名称。

    • 你肯定想清理那个搜索给定字符串出现的函数。

    • 始终使用constlet 定义变量。并将 cmets 添加到代码中。

    • 如果某事物反映了布尔值,则使用一个而不是 01

    • 利用 cmets,这也将有助于其他人查看您的代码(如果您在一段时间后查看您的代码,它也会对您有所帮助)。

    • 使用变量而不是像10 这样的幻数。

    • 即使您的首选语言不是编程语言中使用的那一种,您也应该坚持使用该编程语言使用的那一种。

    所以这是你的代码的修改版本:

    // use an options parameter to make the function more flexible
    function search(str , options) {
      // destructuring the options into variables 
      const {maxCount, pdfCount} = options;
    
      const items = [];
    
      for (let i = 1; i <= pdfCount; i++) {
        items.push({
          p: document.getElementById(`pdf${i}`).innerHTML,
          found: false,
          count: 0
        })
      }
    
      items.forEach(item => {
        let count = 0;
        let currentPosition = 0; // position where to start searching
        let foundAtPosition;
    
        // do-while loop to do at least one search
        do {
          foundAtPosition = item.p.indexOf(str, currentPosition);
          
          // check if we found an occurence
          if (foundAtPosition != -1) {
            // increase the count
            count++;
            // set the current position after the found occurence
            currentPosition = foundAtPosition + str.length;
          }
          
          // if we found more then maxCount we can leave the loop
          if (count > maxCount) {
            break;
          }
    
          // only continue the loop when something was found
          // you could move "count > maxCount" to the while condition
          // but the main purpose of the while loop is to iterate over the content
        } while (foundAtPosition != -1);
    
        // do the composing the information to be set for the item after the for loop, 
        // that makes many things clearer as it is not part of the searching process
    
        // set found to true or false by checking if count is larger then 0
        item.found = count > 0;
    
        
        if (count > maxCount) {
          item.count = `Mehr als ${maxCount}`;
        } else {
          item.count = count;
        }
      })
    
      return items;
    }
    
    console.dir(search('hey', {maxCount: 10, pdfCount: 3}))
    <div id="pdf1">
    heyheyaaheyaaahey
    </div>
    <div id="pdf2">
    heyheyaaheyaaahey
    heyheyaaheyaaahey
    heyheyaaheyaaahey
    
    </div>
    <div id="pdf3">
    foo
    </div>

    您也可以使用str.split([separator[, limit]]) 此处提到的How to count string occurrence in string? 并使用limit 函数。

    但如果你这样做了,你真的需要记录 item.p.split(str, maxCount+2).length - 1 构造,因为否则很难理解。

    // use an options parameter to make the function more flexible
    function search(str , options) {
      // destructuring the options into variables 
      const {maxCount, pdfCount} = options;
    
      const items = [];
    
      for (let i = 1; i <= pdfCount; i++) {
        items.push({
          p: document.getElementById(`pdf${i}`).innerHTML,
          found: false,
          count: 0
        })
      }
    
      items.forEach(item => {
        // use maxCount + 2 to figure out if we have more then max count subtract 1 from length to get the actual count
        const count = item.p.split(str, maxCount+2).length - 1
    
        // set found to true or false by checking if count is larger then 0
        item.found = count > 0;
    
        if (count > maxCount) {
          item.count = `Mehr als ${maxCount}`;
        } else {
          item.count = count;
        }
      })
    
      return items;
    }
    
    console.dir(search('hey', {maxCount: 10, pdfCount: 3}))
    <div id="pdf1">
    heyheyaaheyaaahey
    </div>
    <div id="pdf2">
    heyheyaaheyaaahey
    heyheyaaheyaaahey
    heyheyaaheyaaahey
    
    </div>
    <div id="pdf3">
    foo
    </div>

    【讨论】:

      【解决方案3】:

      你可以使用数组。

      数组,以一种简单的方式,将大量信息放入一个变量中。例如:

      var this_is_an_array=[0,1,2,3,4,5]

      数组从 0 开始计数,所以请注意从 0 开始计数

      w3 学校的更多详细信息:https://www.w3schools.com/js/js_arrays.asp

      【讨论】:

      • 虽然 w3schools 没有像以前那样遭受同样严重的问题,但它们仍然充满了不准确之处。您的链接也是如此。有一次他们说Arrays are Objects … Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.,后来他们说If you use named indexes, JavaScript will redefine the array to an object.。数组是对象,在它们上设置属性(未命名索引)不会改变任何东西。它们不是关联数组,其中命名索引会影响数组的长度/大小。
      猜你喜欢
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      相关资源
      最近更新 更多