如何在第一次迭代中设置值,然后永远不会在Javascript中更改它

时间:2016-12-15 09:54:40

标签: javascript

我正在尝试实施一个研究栏来学习Meteor,JavaScript等......问题在于我想要找到与搜索匹配的第一篇文章但是说“有更多符合您标准的X文章“

我试过这个:

'click .tfbutton'(event){
      var research = document.getElementById('tftextinput').value.toLowerCase();
      var nombreValide = 0;
      var lastArticlePos = 0;

      setTimeout(function(){
        $('.titreArticle').each(function(i, obj) {
          var acutal = obj.textContent.toLowerCase();
            if(acutal.includes(research)){
                nombreValide = nombreValide + 1;
                var position = obj.offsetTop;
                window.scrollTo(0,position);
                document.getElementById('tftextinput').value = "";
            }else{
               document.getElementById('tftextinput').value = "";
              console.log("We can't find an article with your criterias");
            }
        });
        console.log("There is : " + nombreValide + " articles who matchs");
      }, 20)
      },

我希望在第一次迭代时设置lastArticlePos,然后再也不要更改它,但仍然将{1}添加到nombreValide

1 个答案:

答案 0 :(得分:2)

只需使用null对其进行初始化,并仅在null时将其设置为其他内容:

'click .tfbutton'(event){
      var research = document.getElementById('tftextinput').value.toLowerCase();
      var nombreValide = 0;
      var lastArticlePos = null;

      setTimeout(function(){
        $('.titreArticle').each(function(i, obj) {
          var acutal = obj.textContent.toLowerCase();
            if(acutal.includes(research)){
                if (lastArticlePos === null) lastArticlePos = i;
                nombreValide = nombreValide + 1;
                var position = obj.offsetTop;
                window.scrollTo(0,position);
                document.getElementById('tftextinput').value = "";
            }else{
               document.getElementById('tftextinput').value = "";
              console.log("We can't find an article with your criterias");
            }
        });
        console.log("There is : " + nombreValide + " articles who matchs");
        console.log("Article position is : " + (lastArticlePos === null) ? "<No article found>" : lastArticlePos);
      }, 20)
      },