【发布时间】:2015-08-18 13:57:03
【问题描述】:
我在两个单独的函数中有两个命名相同的数组。我假设数组对于每个函数都是本地的,但是第一个函数中的一些值会弄乱另一个函数中的值。当我在第二个函数中更改数组的名称时,它可以工作。如果你问我,似乎违背了范围。为什么我的第一个解决方案不起作用?
问题: 让函数 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"
【问题讨论】:
-
好的,如果你有一个可行的解决方案,你的问题是什么?
-
在strict mode 中运行您的代码,您的至少一个错误将立即显而易见。这就是为什么每个人都应该使用严格模式的原因。
-
尝试用 var tmp = new Array(); 声明数组
标签: javascript arrays scope