在不同函数中具有相同名称的数组

arrays with the same names in different functions

我在两个不同的函数中有两个数组,它们的名称相同。我假设数组对于每个函数都是本地的,但是第一个函数中的一些值弄乱了另一个函数中的值。当我在第二个函数中更改数组的名称时,它起作用了。如果你问我,似乎违反了范围。为什么我的第一个解决方案不起作用?

问题: 让函数 LetterCountI(str) 接受正在传递的 str 参数和 return 具有最多重复字母的第一个单词。例如:"Today, is the greatest day ever!" 应该 return 最大,因为它有 2 个 e(和 2 个 t)并且它出现在 ever 之前也有 2 个 e。如果没有重复字母的单词return -1。单词将以空格分隔。

无效解决方案:

function repeatCount(word) {
    tmp = [];
    for (var i = 0;i<word.length;i++) {
        tmp.push(word.filter(function(value) {return value === word[i]}).length)
    }
    return Math.max.apply(Math,tmp);
}

function LetterCountI(str) {
    tmp = [];
    str = str.split(/[^A-Za-z]/).filter(function(value) {return value != "";});
    for (var i = 0;i<str.length;i++) {
        tmp.push(repeatCount(str[i].split("")));
    }
    console.log(tmp);
    return str[tmp.indexOf(Math.max.apply(Math,tmp))];
}
console.log(LetterCountI("Today, is the greatest day ever!"));

非工作解决方案输出:

Array [ 2, 1, 2, 1 ] 
"Today" 

工作解决方案:

function repeatCount(word) {
    tmp = [];
    for (var i = 0;i<word.length;i++) {
        tmp.push(word.filter(function(value) {return value === word[i]}).length)
    }
    return Math.max.apply(Math,tmp);
}

function LetterCountI(str) {
    count = [];
    str = str.split(/[^A-Za-z]/).filter(function(value) {return value != "";});
    for (var i = 0;i<str.length;i++) {
        count.push(repeatCount(str[i].split("")));
    }
    console.log(count);
    return str[count.indexOf(Math.max.apply(Math,count))];
}
console.log(LetterCountI("Today, is the greatest day ever!"));

工作解决方案输出:

Array [ 1, 1, 1, 2, 1, 2 ]
"greatest"

问题是因为您的 tmp 数组没有在函数中使用 var 关键字定义。定义不带 var 关键字的变量会使它们成为全局范围,因此一个会影响另一个。

要解决这个问题,请使用 var 关键字声明变量,然后它们将像您期望的那样在函数范围内是局部的。

在您的情况下,问题是您将变量 tmp 用作全局变量而不是局部变量。

现在当你在 for 循环中调用 tmp.push(repeatCount(str[i].split(""))); 时,tmp 的值在 repeatCount 中被重置为一个空数组,但由于你使用的是全局变量,它将还影响 LetterCountI 中的 tmp 变量 - http://jsfiddle.net/arunpjohny/e5xxbqbu/2/

所以解决方案是在两个函数中使用 var tmp 将变量声明为局部变量

function repeatCount(word) {
    var tmp = [];
    for (var i = 0; i < word.length; i++) {
        tmp.push(word.filter(function (value) {
            return value === word[i]
        }).length)
    }
    return Math.max.apply(Math, tmp);
}

function LetterCountI(str) {
    var tmp = [];
    str = str.split(/[^A-Za-z]/).filter(function (value) {
        return value != "";
    });
    for (var i = 0; i < str.length; i++) {
        tmp.push(repeatCount(str[i].split("")));
    }
    console.log(tmp);
    return str[tmp.indexOf(Math.max.apply(Math, tmp))];
}
console.log(LetterCountI("Today, is the greatest day ever!"));

演示:Fiddle