繁体   English   中英

不同功能中具有相同名称的数组

[英]arrays with the same names in different functions

我在两个单独的函数中有两个名称相同的数组。 我假设数组在每个函数中都是局部的,但是第一个函数中的某些值会弄乱另一个函数中的值。 当我在第二个函数中更改数组的名称时,它将起作用。 如果您问我,似乎超出了范围。 为什么我的第一个解决方案不起作用?

问题让函数LetterCountI(str)接受传递的str参数,并返回具有最大重复字母数的第一个单词。 例如:“今天,是有史以来最美好的一天!” 应该返回最大,因为它有2个e(和2个t),而且比之前任何一个都具有2个e。 如果没有重复字母的单词,则返回-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用作gloabl变量而不是局部变量。

现在,当您调用tmp.push(repeatCount(str[i].split(""))); 在for循环中,将tmp的值重置为repeatCount的空数组,但是由于您使用的是全局变量,因此也会影响LetterCountItmp变量LetterCountI : //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!"));

演示: 小提琴

暂无
暂无

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

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