我正在努力解决一个棘手的问题。每当有3行(例如3A,3B和3C)时,我想增加变量'count'。我的逻辑仅适用于第一行,但其余部分则失败。这个问题的答案应该是3.有人可以在这里说清楚吗?
function doThis() {
var everySeat = [1A, 1B, 1C, 2A, 2C, 3A, 3B, 3C, 151A, 151B, 151C, 152B, 152C];
var count;
for (i = 1; i <= everySeat.length; i++) {
if (everySeat[i-1] = i + ‘A’ && everySeat[i] = i + ‘B’ && everySeat[i+1] = i + ‘C’) {
count++;
}
}
}
doThis();
答案 0 :(得分:1)
试试这个。工作正常。
function doThis() {
var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'];
var count = 0;
for (var i = 1; i <= everySeat.length-2; i++) {
var prefix = parseInt(everySeat[i-1]);
if (everySeat[i-1] == prefix + 'A' && everySeat[i] == prefix + 'B' && everySeat[i+1] == prefix + 'C') {
count++;
}
}
return count;
}
答案 1 :(得分:0)
首先,您的数组有语法错误。所以尝试下面的代码。
var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'];
var count =0;
for(var i =0; i < everySeat.length ; i++ ){
if(everySeat[i] == i + 'A' && everySeat[i+1] == i + 'B' && everySeat[i+2] == i + 'C' ){
count++;
}
}
console.log(count);
答案 2 :(得分:0)
具有Array.slice()
和String.match()
功能的扩展解决方案:
var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'],
count = 0;
for (var i=0, l=everySeat.length; i < l-2; i++) {
if (String(everySeat.slice(i,i+3)).match(/\d+A,\d+B,\d+C/)) {
count++;
i +=2;
}
}
console.log(count);
答案 3 :(得分:0)
您可以将其转换为字符串,然后匹配所需的子字符串出现。
var everySeat = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'];
var str = everySeat.toString();
var count1 = (str.match(/3A,3B,3C/g) || []).length;
console.log(count1);
答案 4 :(得分:0)
您可以使用哈希表来计算行数,如果行数为3,则可以添加一个哈希表。
此提案也适用于未分类的数据。
var array = ['1A', '1B', '1C', '2A', '2C', '3A', '3B', '3C', '151A', '151B', '151C', '152B', '152C'],
count = Object.create(null),
result = array.reduce(function (r, s) {
var key = s.match(/\d+/)[0];
count[key] = (count[key] || 0) + 1;
return r + (count[key] === 3);
}, 0);
console.log(result);