我正在使用带有D3和firebase的Javascript。不是XML Http请求。
我遇到的困难是如何引入一个while循环和布尔值来在我的消息成功执行后发出警告。
换句话说,当他们超过20%标记时,它应该提醒他们一次,当我刷新页面时,它不应该再次提醒他们。我使用alert作为参考指南,因为作为初学者,这是我可以使用的唯一新手功能。如果有替代方法来实现没有alert()函数的结果但可以警告(通知)用户,那将是很好的。
我在想
var boolean = true
while(...)< - 不确定如何
boolean = false;在我的警报被触发后。因为我是javascript的初学者,所以for循环是必需的,因为数据被读取并放入D3 javascript图表。
我的问题是如何引入while循环来检查条件和布尔值,但仍然有for循环。安全,不应该进入无限循环。
我尝试了各种各样的,但调试很困难。
var data = snapshot.val();
var dataArray = [];
for (var number in data)
{
var percentage = data[number].Percentage;
dataArray.push({valorX: data[number].Team, valorY: percentage});
if(percentage >="0.2" && percentage <= "0.39")
{
alert("Congratulations Team " + data[key].Team + "\nYou have passed the 20% mark!");
} else if (percentage >= "0.4" && percentage <= "0.59")
{
alert("Congratulations Team " + data[key].Team + "\nYou have passed the 40% mark!");
}
else
{
console.log(percentage);
}
}
答案 0 :(得分:2)
使用变量存储状态。使用浏览器存储来保持状态。
var data = snapshot.val();
var dataArray = [];
var status = window.localStorage.getItem('status') ? JSON.parse(window.localStorage.getItem('status')) : {};
for (var number in data)
{
var percentage = data[number].Percentage;
// set team name as key
var key = data[number].Team;
var current = status[key] ? status[key] : {}
dataArray.push({valorX: data[number].Team, valorY: percentage});
if(percentage >="0.2" && percentage <= "0.39" && !current.twenty2fourty)
{
alert("Congratulations Team " + data[key].Team + "\nYou have passed the 20% mark!");
current.twenty2fourty = true;
window.localStorage.setItem('status', JSON.stringify(status));
} else if (percentage >= "0.4" && percentage <= "0.59" && !current.fourty2sixty)
{
alert("Congratulations Team " + data[key].Team + "\nYou have passed the 40% mark!");
current.fourty2sixty = true;
window.localStorage.setItem('status', JSON.stringify(status));
}
else
{
console.log(percentage);
}
}
然后状态的格式应为:
{
"team1": {"twenty2fourty" : true},
"team2": {"fourty2sixty" : true},
"team3": {"twenty2fourty" : true, "fourty2sixty": true}
}
答案 1 :(得分:0)
var alertObj = {};
for (var number in data)
{
var percentage = data[number].Percentage;
var key;
dataArray.push({valorX: data[number].Team, valorY: percentage});
if(percentage >="0.2" && percentage <= "0.39")
{
key = data[number].Team + "--20%"
if(!alertObj[key]){
alert("Congratulations Team " + data[key].Team + "\nYou have passed the 20% mark!");
}
else {
alertObj[key] = true;
}
} else if (percentage >= "0.4" && percentage <= "0.59")
{
key = data[number].Team + "--40%"
if(!alertObj[key]){
alert("Congratulations Team " + data[key].Team + "\nYou have passed the 40% mark!");
}
else {
alertObj[key] = true;
}
}
else
{
console.log(percentage);
}
}
密钥的格式为“{teamname} - 20”,如果是20%。 通过这种方式,您可以跟踪哪个团队被告知哪个标记。