我想检查数据数组中的元素并显示为" O"如果它包含表中的月份和数字。因此,对于" Jan-1",Array1[0][0]
应显示为" O"但是下面的代码不起作用。有人能帮我吗?
var Data = ["Jan-1", "Feb-4", "Apr-5"];
var Month= ["Jan", "Feb", "Mar", "Apr", "May"];
var Number = ["1", "2", "3", "4", "5"];
var Array1 = [[]];
for (var k = 0; k < Data.length; k++) {
var split = Data[k].split("-");
for (var z = 0; z < Month.length; z++) {
for (var s = 0; s < Number.length; s++) {
if (Month[z] == split[0] && period[s] == split[1]) {
Array1[z][s] = "O";
} else {
Array1[z][s] = "X";
}
}
}
}
number/month | Jan | Feb | Mar | Apr | May
------------------------------------------------------
1 | O | X | X | X | X
2 | X | X | X | X | X
3 | X | X | X | X | X
4 | X | O | X | X | X
5 | X | X | X | O | X
答案 0 :(得分:1)
您应该遍历Number
和Month
数组,并且每次都检查Month[j] + "-" + Number[i]
数组中是否有Data
组合:
var Data = ["Jan-1", "Feb-4", "Apr-5"];
var Month = ["Jan", "Feb", "Mar", "Apr", "May"];
var Number = ["1", "2", "3", "4", "5"];
var result = [];
for (var i = 0; i < Number.length; i++) { // foreach number
result[i] = []; // create a row for this current number
for (var j = 0; j <Month.length; j++) { // for each month
if (Data.indexOf(Month[j] + "-" + Number[i]) !== -1) { // check if the current combination (currentMonth-currentNumber) is in the Data array
result[i][j] = "O";
} else {
result[i][j] = "X";
}
}
}
result.forEach(function(row) {
console.log(row.join(" | "));
});
&#13;
答案 1 :(得分:1)
分析您的代码:
var Data = ["Jan-1", "Feb-4", "Apr-5"];
var Month= ["Jan", "Feb", "Mar", "Apr", "May"];
var Number = ["1", "2", "3", "4", "5"];
var Array1 = [ ["X","X","X","X","X"], ["X","X","X","X","X"], "X","X","X","X","X"], ["X","X","X","X","X"], ["X","X","X","X","X"]]; //Initialise all elements to "X" by default. We shall change only those indexes that match.
for (var k = 0; k < Data.length; k++) {
var split = Data[k].split("-");
for (var z = 0; z < Month.length; z++) {
for (var s = 0; s < Number.length; s++) {
if (Month[z] == split[0] && Number[s] == split[1]) {
Array1[z][s] = "O";
} else {
//Array1[z][s] = "X"; Do not change here as the loop will go over the entire array once for each data. Hence previous matches would get lost!!
}
}
}
}
最后,console.table(Array1);
打印值。
评论:在初始化时,您将行声明为月份和列数,但是期望相反的输出。因此,要生成预期输出,打印横向形式或在定义值时更改:
if (Month[z] == split[0] && Number[s] == split[1]) {
Array1[s][z] = "O";
}
答案 2 :(得分:0)
您可以使用给定数据获取对象并迭代month
和number
以返回包含'O'
或'X'
信息的新数组。
var data = ["Jan-1", "Feb-4", "Apr-5"],
month = ["Jan", "Feb", "Mar", "Apr", "May"],
number = ["1", "2", "3", "4", "5"],
result = [],
hash = Object.create(null);
data.forEach(function(s) {
var [m, d] = s.split('-');
hash[m] = hash[m] || {};
hash[m][d] = true;
});
result = month.map(function (m, z) {
return number.map(function (s) {
return (hash[m] || {})[s] ? 'O' : 'X';
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }