谁能看出我的 Javascript 有什么问题吗?

发布于 2024-08-10 17:02:56 字数 886 浏览 8 评论 0原文

我编写了以下内容:

var pages=["[www.google.co.uk] This is the WWW. ","[www.yahoo.co.uk] This is also the WWW. "];
function findScoresC(s){ 
var scores=[];
var words=[];
var wordScore;
var indexScore=[];
s=s.toLowerCase();
for(i=0;i<pages.length; i++){
   var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
   words=lowerCaseContents.split(" ");
   for(i=0;i<words.length;i++){
    if(words[i].match(s)){
        wordScore=1;
        indexScore[i]=indexScore[i]+1};
   scores[i] =indexScore[i]}};
return scores;
}
alert(findScoresC("w"));

该函数旨在返回一个数组(“scores”),其中数组的每个索引是在“pages”数组的每个索引中找到字符串 s 的次数,不包括正方形内的内容括号 - 但是,在每个单词中只找到一次字符串 s 。所以理想情况下,分数的第一个索引应该是 1,因为我用字母 w 调用了该函数,并且我只希望它在第一个页面索引中找到“WWW”的第一个 w - 如果这有意义的话。

到目前为止,我已经非常困惑了,所以我不知道为什么该函数返回“,,,,”而不是每个分数索引的数值 - 有什么想法吗?

谢谢

I have written the following:

var pages=["[www.google.co.uk] This is the WWW. ","[www.yahoo.co.uk] This is also the WWW. "];
function findScoresC(s){ 
var scores=[];
var words=[];
var wordScore;
var indexScore=[];
s=s.toLowerCase();
for(i=0;i<pages.length; i++){
   var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
   words=lowerCaseContents.split(" ");
   for(i=0;i<words.length;i++){
    if(words[i].match(s)){
        wordScore=1;
        indexScore[i]=indexScore[i]+1};
   scores[i] =indexScore[i]}};
return scores;
}
alert(findScoresC("w"));

The function aims to return an array ("scores") where each index of the array is the number of times the string s is found in each index of the "pages" array, excluding what is inside the square brackets - however, only finding the string s once within each word. So ideally, the first index of scores would be 1, because I have called the function with the letter w, and i would only like it to find the first w of "WWW" in the first index of pages - if this makes sense.

I have confused myself pretty epically in getting this far, so I have no idea why the function is returning ",,,," rather than numerical values for each index of scores - any ideas?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

哆兒滾 2024-08-17 17:02:56

for 循环退出时,i 等于 words.length,它比 indexScore.每次都没有向 scores[i] 分配任何内容。

When your for loop exits, i is equal to words.length, which is one greater than the last index of indexScore. You are assigning nothing at all to scores[i] each time through.

你在看孤独的风景 2024-08-17 17:02:56

这可能是因为您有一个具有相同索引变量的嵌套 for 循环。

It might be because you have a nested for loop with the same index variable.

走过海棠暮 2024-08-17 17:02:56
var pages=["[www.google.co.uk] This is the WWW. ","[www.yahoo.co.uk] This is also the WWW. ";

function findScoresC(s){ 
  var scores=[];
  var words=[];
  s=s.toLowerCase();
  for(i=0;i<pages.length; i++)
  {
     scores[i]=0;
     var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
     words=lowerCaseContents.split(" ");
     for(j=0;j<words.length;j++)
     {
        if(words[j].match(s))
        {
          scores[i] += 1;
        }
      }
  }
  return scores;
}
alert(findScoresC("w"));

有几件事。我将内部索引的“i”替换为“j”。右括号后不需要加分号。说明后应该有一个分号(缺少几个分号)。

可能主要问题(在“i”问题之后)是分数[i]应该设置在内循环之外。如果将 cosing 括号分成单独的行,而不是像“scores[i] =indexScore[i]}};”,这会更清楚。

事实证明,变量 indexScore 不是必需的。这使我可以将 scores[i] 引入内部循环以直接累积单词点击量。

最后,我更愿意将 pages 变量作为参数传递给函数,而不是假设它在全局空间中可用。如果可以的话,我倾向于避免全局变量。

var pages = [...];
function findScoresC(pages, s)
{
   ...
}
alert(findScoresC(pages, "w"));
var pages=["[www.google.co.uk] This is the WWW. ","[www.yahoo.co.uk] This is also the WWW. ";

function findScoresC(s){ 
  var scores=[];
  var words=[];
  s=s.toLowerCase();
  for(i=0;i<pages.length; i++)
  {
     scores[i]=0;
     var lowerCaseContents=(pages[i].substring(pages[i].indexOf("]")+1,pages[i].lastIndexOf(" "))).toLowerCase();
     words=lowerCaseContents.split(" ");
     for(j=0;j<words.length;j++)
     {
        if(words[j].match(s))
        {
          scores[i] += 1;
        }
      }
  }
  return scores;
}
alert(findScoresC("w"));

There were a few things. I replaced "i" with "j" for the inner index. You don't require a semicolon after a closing paren. You should have a semicolon after instructions (a couple were missing).

Probably the main issue (after the "i" issue) was that scores[i] should have been set outside the inner loop. This would have been clearer if the cosing parens had been separated out onto separate lines, instead of like "scores[i] =indexScore[i]}};".

It turned out that the variable indexScore was not required. That allowed me to bring scores[i] inside the inner loop to accumulate word hits directly.

Finally, I would prefer to communicate the pages variable to the function as an argument than to assume that it is available in the global space. I tend to avoid globals if I can.

var pages = [...];
function findScoresC(pages, s)
{
   ...
}
alert(findScoresC(pages, "w"));
虐人心 2024-08-17 17:02:56

这是你的功能修复。它返回 [1,1] 这似乎就是您想要的。我的笔记都在代码里了

var pages=["[www.google.co.uk] This is the WWW. ","[www.yahoo.co.uk] This is also the WWW. "];

function findScoresC(s){ 
    var scores = [],
        words = [],
        wordScore;
        // indexScore = [] <- this doesn't seem necessary
    s = s.toLowerCase();

    // Make sure to use `var i` and not just `i`; otherwise, you are creating a global variable.
    for ( var i=0; i<pages.length; i++ ) {
        // Initialize me!
        scores.push(0);

        var lowerCaseContents = pages[i].substring(
            pages[i].indexOf("]") + 1, pages[i].lastIndexOf(" ")
        ).toLowerCase();
        words = lowerCaseContents.split(" ");

        // You were using `i` for this loop as well.  No can do.
        for ( var j=0; j<words.length; j++) {
            if ( words[j].match(s) ) {
               // wordScore = 1;  <- I don't know what you're using this for
               scores[i]++;
            }
        }
    };

    return scores;
}

console.log(findScoresC("w"));

Here's you're function fixed. It returns [1,1] which appears to be what you were going for. My notes are in the code.

var pages=["[www.google.co.uk] This is the WWW. ","[www.yahoo.co.uk] This is also the WWW. "];

function findScoresC(s){ 
    var scores = [],
        words = [],
        wordScore;
        // indexScore = [] <- this doesn't seem necessary
    s = s.toLowerCase();

    // Make sure to use `var i` and not just `i`; otherwise, you are creating a global variable.
    for ( var i=0; i<pages.length; i++ ) {
        // Initialize me!
        scores.push(0);

        var lowerCaseContents = pages[i].substring(
            pages[i].indexOf("]") + 1, pages[i].lastIndexOf(" ")
        ).toLowerCase();
        words = lowerCaseContents.split(" ");

        // You were using `i` for this loop as well.  No can do.
        for ( var j=0; j<words.length; j++) {
            if ( words[j].match(s) ) {
               // wordScore = 1;  <- I don't know what you're using this for
               scores[i]++;
            }
        }
    };

    return scores;
}

console.log(findScoresC("w"));
财迷小姐 2024-08-17 17:02:56

这是一个小函数,用于计算子字符串“subStr”在“str”中出现的次数,不计算[...]

function substrCount(str, subStr) {
   var str = str.replace(/\[.+?\]/g, "");
   var del = str.toLowerCase().split(subStr.toLowerCase()).join("");
   return (str.length - del.length) / subStr.length;
}

其余的很明显;)

//编辑:这就是将此函数应用于数组的方式

 var someArray = ["whatever", "something", "else" ];
 var counter = [];
 for(var i = 0; i < someArray; i++)
      counter[i] = substrCount(someArray[i], "something");
      // or, to count only one match, i.e. just to test if a substring is present
      counter[i] = substrCount(someArray[i], "something") > 0;

here's a small function that counts how many times substring "subStr" occurs in "str", not counting [...]

function substrCount(str, subStr) {
   var str = str.replace(/\[.+?\]/g, "");
   var del = str.toLowerCase().split(subStr.toLowerCase()).join("");
   return (str.length - del.length) / subStr.length;
}

the rest is obvious ;)

// edit: this is how you apply this function to an array

 var someArray = ["whatever", "something", "else" ];
 var counter = [];
 for(var i = 0; i < someArray; i++)
      counter[i] = substrCount(someArray[i], "something");
      // or, to count only one match, i.e. just to test if a substring is present
      counter[i] = substrCount(someArray[i], "something") > 0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文