Good evening,
I am using Blockly to learn to programm.
In the exercise part of the code is not executed correctly. If "maandloon" is above > 2000, then there is a reduction of 25% on 'Kindergeld'. However if the result after the reduction is below 25 euro per child, then there is no reduction.
The problem is that calculation keeps using the 25% when maandloon >2000, even if the result afer reduction is below 25 euro per child.
This is my code:
var aantalKinderen, maandloon, kindergeld, kindergeldBasis, toeslag3ekind, toeslag5ekind, i;
do {
aantalKinderen=parseInt((parseFloat((output = window.prompt('Hoeveel kinderen?')) ? output : "")));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(aantalKinderen));
do {
maandloon=(parseFloat((output = window.prompt('Wat is het maandloon?')) ? output : ""));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(maandloon));
kindergeldBasis = 25;
toeslag3ekind = 12.5;
toeslag5ekind = 7.5;
kindergeld = kindergeldBasis * aantalKinderen;
if (aantalKinderen > 2) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind;
}
if (aantalKinderen > 4) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind + (aantalKinderen - 4) * toeslag5ekind;
}
if (maandloon <= 500) {
kindergeld = kindergeld * 1.25;
}
if (maandloon > 2000) {
kindergeld = kindergeld * 0.75;
} else {
if ((kindergeld * 0.75) / aantalKinderen < 25) {
kindergeld = kindergeld;
}
}
window.alert(String('Het kindergeld bedraagt ') + String(kindergeld)+'\n');
Can someone help me?
Thank you.
From what it sounds like you want to move your extra if check into the > 2000 statement. Otherwise it won't fire. Your if else statement is linear. It doesn't hit your else after > 2000 unless the conditional hasn't been matched by any of the previous if statements and the value is less than 2000. It does not run regardless or when the value was changed by a previous if condition.
var aantalKinderen, maandloon, kindergeld, kindergeldBasis, toeslag3ekind, toeslag5ekind, i;
do {
aantalKinderen=parseInt((parseFloat((output = window.prompt('Hoeveel kinderen?')) ? output : "")));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(aantalKinderen));
do {
maandloon=(parseFloat((output = window.prompt('Wat is het maandloon?')) ? output : ""));
var blocktype_number = true;
if (output == null) {
window.alert("No empty input allowed");
break;
}
} while(isNaN(maandloon));
kindergeldBasis = 25;
toeslag3ekind = 12.5;
toeslag5ekind = 7.5;
kindergeld = kindergeldBasis * aantalKinderen;
if (aantalKinderen > 2) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind;
}
if (aantalKinderen > 4) {
kindergeld = kindergeldBasis * aantalKinderen + (aantalKinderen - 2) * toeslag3ekind + (aantalKinderen - 4) * toeslag5ekind;
}
if (maandloon <= 500) {
kindergeld = kindergeld * 1.25;
}
if (maandloon > 2000) {
kindergeld = kindergeld * 0.75;
if (kindergeld / aantalKinderen < 25) {
kindergeld = 25;
}
}
window.alert(String('Het kindergeld bedraagt ') + String(kindergeld)+'\n');
Related
I'm trying to build a simple game and having hard time with collision detecting. I want the alert to be popped up when the hero hits the virus and below is my js code. I'm not sure if my collision detect logic is wrong too. The viruses are moving randomly and I used CSS transition for them to move gradually.
var henryLocation = {
top: 700,
left: 700
}
document.onkeydown = function (evt) {
// console.log(evt)
if (evt.keyCode === 38 && henryLocation.top > 10) {
henryLocation.top = henryLocation.top - 25
} else if (evt.keyCode === 40 && henryLocation.top < 700) {
henryLocation.top = henryLocation.top + 25
} else if (evt.keyCode === 37 && henryLocation.left > 10) {
henryLocation.left = henryLocation.left - 25
} else if (evt.keyCode === 39 && henryLocation.left < 1360) {
henryLocation.left = henryLocation.left + 25
}
moveHenry()
}
function moveHenry () {
document.getElementById('henry').style.top = henryLocation.top + 'px'
document.getElementById('henry').style.left = henryLocation.left + 'px'
}
const startBtn = document.getElementById('btn-start')
startBtn.addEventListener("click", theGame)
function theGame () {
const startGame = setInterval(moveCorona, 1300)
function moveCorona () {
const theCorona = document.getElementById('corona')
const theCorona1 = document.getElementById('corona1')
const theCorona2 = document.getElementById('corona2')
const w = 1300, h = 600
theCorona.style.top = Math.floor(Math.random() * h) + 'px'
theCorona.style.left = Math.floor(Math.random() * w) + 'px'
theCorona1.style.top = Math.floor(Math.random() * h) + 'px'
theCorona1.style.left = Math.floor(Math.random() * w) + 'px'
theCorona2.style.top = Math.floor(Math.random() * h) + 'px'
theCorona2.style.left = Math.floor(Math.random() * w) + 'px'
function collisionDetect () {
var theHenry = henry.getBoundingClientRect();
var theCorona = corona.getBoundingClientRect();
if ((theCorona.top > theHenry.top && theCorona.top < theHenry.bottom) || (theCorona.bottom > theHenry.top && theCorona.bottom < theHenry.bottom)) {
let verticalCollision = true
} else {
let verticalCollision = false
}
if ((theCorona.right > theHenry.left && theCorona.right < theHenry.right) || (theCorona.left < theHenry.right && theCorona.left > theHenry.left)) {
let horizontalCollision = true
} else {
let horizontalCollision = false
}
if (verticalCollision && horizontalCollision) {
alert('collision detected')
} else {
console.log('Game goes on')
}
}
// collisionDetect()
}
}
function gameLoop () {
setTimeout(gameLoop, 1000)
}
gameLoop()
I have a large number issue here. I'm using the nFormatter for large numbers in javascript but i have no idea how to use it with my existing code.
Here is the formatter im using.
function nFormatter(num) {
if (num >= 1000000000000) {
return (num / 1000000000000).toFixed(1).replace(/\.0$/, '') + 'Trillion';
}
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'Billion';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'Million';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'Thousand';
}
return num;
}
nFormatter;
I need to add this code to my other code but i am not sure how i am going to do this.
Here is my current code.
var gameProfit = 5000;
var tinyOwned = 0;
var tinyCost = 5000;
var tinyIncome = 0;
function tinyGamePlay() {
if (gameProfit >= tinyCost) {
tinyOwned++;
gameProfit -= tinyCost;
tinyIncome = 15000 * tinyOwned;
tinyCost = 5000 * tinyOwned;
document.getElementById('tiny-owned').innerHTML = tinyOwned;
document.getElementById('tiny-income').innerHTML = "Income : $ " + tinyIncome;
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + tinyCost;
document.getElementById('currentProfit').innerHTML = "Profit : $ " + gameProfit;
}
}
tinyGamePlay;
So all of the my variable will be more than 1000 at one point so the formatter needs to be used on all my variables.
I dont mind using a JS plugin either if anyone knows of something that could help,
Can anyone help please?
You just need to call this nFormatter function when you are printing the output, see snipped below, for bigger numbers you can use http://jsfromhell.com/classes/bignumber :
function nFormatter(num) {
if (num >= 1000000000000) {
return (num / 1000000000000).toFixed(1).replace(/\.0$/, '') + ' Trillion';
}
if (num >= 1000000000) {
return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + ' Billion';
}
if (num >= 1000000) {
return (num / 1000000).toFixed(1).replace(/\.0$/, '') + ' Million';
}
if (num >= 1000) {
return (num / 1000).toFixed(1).replace(/\.0$/, '') + ' Thousand';
}
return num;
}
var gameProfit = 5100;
var tinyOwned = 0;
var tinyCost = 5000;
var tinyIncome = 0;
function tinyGamePlay() {
if (gameProfit >= tinyCost) {
tinyOwned++;
gameProfit -= tinyCost;
tinyIncome = 15000 * tinyOwned;
tinyCost = 5000 * tinyOwned;
console.log(tinyCost);
document.getElementById('tiny-owned').innerHTML = nFormatter(tinyOwned);
document.getElementById('tiny-income').innerHTML = "Income : $ " + nFormatter(tinyIncome);
document.getElementById('tiny-cost').innerHTML = "Next Cost : $ " + nFormatter(tinyCost);
document.getElementById('currentProfit').innerHTML = "Profit : $ " + nFormatter(gameProfit);
}
}
tinyGamePlay();
<p id="tiny-owned"></p>
<p id="tiny-income"></p>
<p id="tiny-cost"></p>
<p id="currentProfit"></p>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am making a star wars game with HTML, CSS and JS. It should look a little bit like this game: https://www.gog.com/game/star_wars_xwing_vs_tie_fighter
Now I want to make it like a kind of game in which you have to shoot at enemy ships. for these ships I want to use this image: http://vignette4.wikia.nocookie.net/starwars/images/0/0a/TIE_Advanced_x1_starfighter.png/revision/latest?cb=20150310124250
Now her this is my questions:
How can I make it look like the ship in this image is getting closer to you? So that it appears in the distance really small and gets closer to you and becomes bigger, so that it looks like it is flying towards you?
I tried to use z-index but that did not work.
Also pls don't mind the code for I have been working on it for a long time and it finally works the way I want it to, but if it is a hinder in any further progress feel free to tell me what I need to add/change/remove or whatsoever.
Also I have been looking around on the internet how I could possibly make something like a star wars game but for example on this site the obly thing I could find related to star wars was how to make the crawling introduction but that is not what I am looking for:)
Number.prototype.clamp = function(min, max) {
'use strict';
return Math.max(min, Math.min(this, max));
};
var url = document.location.href;
var n = parseInt((url.indexOf('n=') != -1) ? url.substring(url.indexOf('n=') + 2, ((url.substring(url.indexOf('n=') + 2, url.length)).indexOf('&') != -1) ? url.indexOf('n=') + 2 + (url.substring(url.indexOf('n=') + 2, url.length)).indexOf('&') : url.length) : 512 * 4);
var star = new Array(n);
var hyperspace = 0;
var lol = {}
lol.id = 'starfield';
lol.pr = {
w: 1,
h: 1
};
lol.zr = 256;
lol.timer = 0;
lol.spd = 1;
lol.rid = false;
lol.cvs = false;
lol.ctx = false;
lol.util = {
isboolean: function(v) {
if (typeof v === 'boolean') {
return true;
}
return false;
},
isstring: function(v) {
if (typeof v === 'string') {
return true;
}
return false;
},
isobject: function(v) {
if (typeof v === 'object') {
return true;
}
return false;
},
isfunction: function(v) {
if (typeof v === 'function') {
return true;
}
return false;
},
isempty: function(obj) {
if (window.Object.getOwnPropertyNames(obj).length === 0) {
return true;
}
return false;
},
isffx: function() {
return (/firefox/i).test(window.navigator.userAgent);
},
copy: function(v) {
return v.slice(0);
},
clone: function(v) {
return Object.create({
x: v.x,
y: v.y,
z: v.z
});
},
sign: function(v) {
v = parseFloat(Number(v).toFixed(1));
if (v === 0) {
return ' ';
}
if (v < 0) {
return '';
}
if (v > 0) {
return '+';
}
},
random: function(n) {
var i = 0,
type, start, len, rnd = '';
while (i < n) {
type = Math.round(Math.random() * 2);
if (type === 0) {
start = 48;
len = 10;
} else {
start = (Math.round(Math.random() * 2) % 2 === 0) ? 65 : 97;
len = 26;
}
rnd += String.fromCharCode(start + Math.floor(Math.random() * len));
i += 1;
}
return rnd;
},
interpolate: function(from, to, n, i) {
return from + (to - from) / n * i;
},
time: function() {
return (new Date()).getTime();
}
};
lol.i = function(id) {
return window.document.getElementById(String(id));
};
lol.el = function(el) {
return window.document.createElement(String(el));
};
lol.tn = function(txt) {
return window.document.createTextNode(String(txt));
};
function $r(parent, child) {
(document.getElementById(parent)).removeChild(document.getElementById(child));
}
function $t(name) {
return document.getElementsByTagName(name);
}
function $c(code) {
return String.fromCharCode(code);
}
function $h(value) {
return ('0' + Math.max(0, Math.min(255, Math.round(value))).toString(16)).slice(-2);
}
function _i(id, value) {
$t('div')[id].innerHTML += value;
}
function _h(value) {
return !hires ? value : Math.round(value / 2);
}
function get_screen_size() {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
return Array(w, h);
};
lol.init = function() {
window.addEventListener('resize', lol.resize, false);
window.addEventListener('mousemove', lol.mouse.move, false);
var e = lol.util.isffx() ? 'DOMMouseScroll' : 'mousewheel';
window.addEventListener(e, lol.mouse.wheel, false);
window.addEventListener('keypress', lol.key, false);
lol.viewport();
lol.resize();
for (var i = 0; i < n; i++) {
star[i] = new Array(5);
star[i][0] = Math.random() * lol.w * 3 - lol.x * 3;
star[i][1] = Math.random() * lol.h * 3 - lol.y * 3;
star[i][2] = Math.round(Math.random() * lol.z);
star[i][3] = lol.x;
star[i][4] = lol.y;
}
lol.anim.start();
};
lol.viewport = function() {
var el = lol.el('div');
el.id = lol.id;
el.style.position = 'absolute';
window.document.body.appendChild(el);
lol.cvs = lol.el('canvas');
lol.cvs.id = lol.id + '-viewport';
lol.cvs.style.position = 'absolute';
el.appendChild(lol.cvs);
lol.ctx = lol.cvs.getContext('2d');
};
lol.resize = function() {
var w = window.innerWidth,
h = window.innerHeight,
el = lol.i(lol.id);
lol.w = (w + lol.pr.w - w % lol.pr.w) / lol.pr.w;
lol.w += lol.w % 2;
lol.h = (h + lol.pr.h - h % lol.pr.h) / lol.pr.h;
lol.h += lol.h % 2;
lol.x = Math.round(w / 2);
lol.y = Math.round(h / 2);
lol.z = (w + h) / 2;
lol.r = 1 / lol.z;
el.width = lol.w * lol.pr.w;
el.height = lol.h * lol.pr.h;
lol.cvs.width = lol.w * lol.pr.w;
lol.cvs.height = lol.h * lol.pr.h;
lol.cvs.style.backgroundColor = '#000';
lol.ctx.scale(lol.pr.w, lol.pr.h);
lol.mouse.o = {
x: lol.x,
y: lol.y
};
};
lol.anim = {
update: function() {
var c;
lol.ctx.fillStyle = 'rgba(0,0,0,0.5)';
if (hyperspace === 1) {
lol.spd = lol.spd * 1.015;
lol.zr = lol.zr * 0.99;
c = Math.round(lol.spd * 4);
lol.ctx.fillStyle = 'rgba(' + c + ',' + c + ',' + c + ',0.5)';
if (lol.spd > 64) {
lol.ctx.fillStyle = 'rgba(0,0,0,0.5)';
lol.spd = 16;
lol.zr = 256;
hyperspace = 2;
}
}
if (hyperspace === 2) {
if (lol.spd > 1) {
lol.spd *= 0.99;
} else {
lol.spd = 1;
hyperspace = 0;
}
}
lol.ctx.fillRect(0, 0, lol.w, lol.h);
for (var i = 0; i < n; i++) {
var test = true,
x2 = star[i][3],
y2 = star[i][4];
star[i][0] += lol.mouse.p.x * 0.1;
if (star[i][0] > lol.x * 3) {
star[i][0] -= lol.w * 3;
test = false;
}
if (star[i][0] < -lol.x * 3) {
star[i][0] += lol.w * 3;
test = false;
}
star[i][1] += lol.mouse.p.y * 0.1;
if (star[i][1] > lol.y * 3) {
star[i][1] -= lol.h * 3;
test = false;
}
if (star[i][1] < -lol.y * 3) {
star[i][1] += lol.h * 3;
test = false;
}
star[i][2] -= lol.spd;
if (star[i][2] > lol.z) {
star[i][2] -= lol.z;
test = false;
}
if (star[i][2] < 0) {
star[i][2] += lol.z;
test = false;
}
star[i][3] = lol.x + (star[i][0] / star[i][2]) * lol.zr;
star[i][4] = lol.y + (star[i][1] / star[i][2]) * lol.zr;
if (test) {
c = 1 - lol.r * star[i][2];
lol.ctx.fillStyle = 'rgba(255,255,255,' + c + ')';
lol.ctx.strokeStyle = 'rgba(255,255,255,' + (c / 4) + ')';
lol.ctx.lineWidth = (1 - lol.r * star[i][2]) * 1.5;
lol.ctx.beginPath();
lol.ctx.moveTo(x2, y2);
lol.ctx.lineTo(star[i][3], star[i][4]);
lol.ctx.rect(star[i][3] - 0.75, star[i][4] - 0.75, 1.5, 1.5);
lol.ctx.closePath();
lol.ctx.stroke();
lol.ctx.fill();
}
}
lol.rid = window.requestAnimationFrame(lol.anim.update);
},
start: function() {
lol.anim.update();
},
stop: function() {
window.cancelAnimationFrame(lol.rid);
lol.rid = false;
},
pause: function() {
lol.anim[lol.rid ? 'stop' : 'start']();
}
};
lol.mouse = {
p: {
x: 0,
y: 0
},
o: {
x: 0,
y: 0
},
click: false,
move: function(e) {
e = e || window.event;
lol.mouse.p.x = ((e.pageX - lol.mouse.o.x) / window.innerWidth) * 256;
lol.mouse.p.y = ((e.pageY - lol.mouse.o.y) / window.innerHeight) * 256;
e.preventDefault();
},
wheel: function(e) {
e = e || window.event;
var delta = e.wheelDelta / 120;
lol.spd -= delta * 0.1;
e.preventDefault();
}
};
lol.key = function(e) {
e = e || window.event;
console.log(e.keyCode);
switch (e.keyCode) {
case 13:
lol.anim.pause();
break;
case 32:
hyperspace = 1;
break;
}
};
lol.init();
body {
margin: 0px;
padding: 0px;
overflow: hidden;
z-index: -1
}
#footer {
text-align: center;
background-color: black;
color: white;
}
#div {
background-color: black;
text-align: center;
}
<footer id="footer">Galaxy Defender
<br>Mohan Bloxs</br>
</footer>
For some reason, the div tags are not displayed in the webpage when the program is run. I tested every other component and have figured out that the problem is that the setting of the value of the div tags is in an if statement. The only problem is that I do not know how to fix the problem and still have the program run the way I want it to.
<div id="answerDisplay"></div>
<div id="correctOrNot"></div>
<script>
var div
var div2
var rightAnswer
var problemNum =Math.floor((Math.random() * 3) + 1);
if (problemNum == 1){
rightAnswer = 14;
div = document.getElementById("answerDisplay");
div.textContent = "4 + 2 * (10 - 3 * 2) / 4 + 8 = ?";
}
else if (problemNum == 2){
rightAnswer = 8;
div = document.getElementById("answerDisplay");
div.textContent = "(6 - 3) * 2 + (3^2 - 5) / 2 = ?";
}
else if (problemNum == 3){
rightAnswer = 6;
div = document.getElementById("answerDisplay");
div.textContent = "5 - 3 + 4^2 / (8 - 4 / 2) = ?";
}
else if (problemNum == 4){
rightAnswer = 3;
div = document.getElementById("answerDisplay");
div.textContent = "5^2 - (6 * 2) * 2 * (5 - 2) = ?";
}
function checkRightAnswer (){
var answer = document.getElementById('Input').value
if (problemNum == 1 && answer == 14){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else if (problemNum == 2 && answer == 8){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else if (problemNum == 3 && answer == 6){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else if (problemNum == 4 && answer == 3){
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum =Math.floor((Math.random() * 3) + 1);
}
else {
div2 = document.getElementById("correctOrNot");
div2.textContent = "Incorrect, try again";
}
}
</script>
Your code seems to work fine. I don't see the input container included in the code snippet you provided. Perhaps you need to make sure the id is correct there? I cleaned up the code a bit:
var div, div2, rightAnswer, problemNum = Math.floor((Math.random() * 3) + 1);
if (problemNum === 1) {
rightAnswer = 14;
div = document.getElementById("answerDisplay");
div.textContent = "4 + 2 * (10 - 3 * 2) / 4 + 8 = ?";
} else if (problemNum === 2) {
rightAnswer = 8;
div = document.getElementById("answerDisplay");
div.textContent = "(6 - 3) * 2 + (3^2 - 5) / 2 = ?";
} else if (problemNum === 3) {
rightAnswer = 6;
div = document.getElementById("answerDisplay");
div.textContent = "5 - 3 + 4^2 / (8 - 4 / 2) = ?";
} else if (problemNum === 4) {
rightAnswer = 3;
div = document.getElementById("answerDisplay");
div.textContent = "5^2 - (6 * 2) * 2 * (5 - 2) = ?";
}
function checkRightAnswer() {
var answer = document.getElementById('Input').value;
if (problemNum === 1 && answer === 14) {
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum = Math.floor((Math.random() * 3) + 1);
} else if (problemNum === 2 && answer === 8) {
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum = Math.floor((Math.random() * 3) + 1);
} else if (problemNum === 3 && answer === 6) {
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum = Math.floor((Math.random() * 3) + 1);
} else if (problemNum === 4 && answer === 3) {
div2 = document.getElementById("correctOrNot");
div2.textContent = "Correct";
problemNum = Math.floor((Math.random() * 3) + 1);
} else {
div2 = document.getElementById("correctOrNot");
div2.textContent = "Incorrect, try again";
}
}
<div id="answerDisplay"></div>
<div id="correctOrNot"></div>
<input type="text" id="Input" />
Here is a way you would rewrite it to use an array of objects as ErikE suggested in his comment.
var questions = [
{
q: "4 + 2 * (10 - 3 * 2) / 4 + 8 = ?",
a: 14
},
{
q: "(6 - 3) * 2 + (3^2 - 5) / 2 = ?",
a: 8
},
{
q: "5 - 3 + 4^2 / (8 - 4 / 2) = ?",
a: 6
},
{
q: "5^2 - (6 * 2) * 2 * (5 - 2) = ?",
a: 3
}
],
currentQuestion, // the index of the current question will
// be stored here so we can look up the answer later
timerId,
doc = document,
elQuestion = doc.getElementById('question')
elAnswer = doc.getElementById('answer'),
elUserAnswer = doc.getElementById('user-answer'),
elCheck = doc.getElementById('check'),
displayQuestion = function (index) {
currentQuestion = index;
elQuestion.textContent = questions[index].q;
},
displayRandomQuestion = function () {
displayQuestion(Math.floor(Math.random() * questions.length));
},
removeAnswer = function () {
timerId = setTimeout(function () {
elAnswer.textContent = ''
}, 1000);
},
checkAnswer = function () {
var userAnswer = elUserAnswer.value;
clearTimeout(timerId);
// the '' + explicitly converts the .a to a string because userAnswer will be a string
// using the strict comparison operator (===) is a good habit to get into
if (userAnswer === '' + questions[currentQuestion].a) {
elAnswer.textContent = 'Correct!';
displayRandomQuestion();
} else {
elAnswer.textContent = 'Incorrect, try again';
}
removeAnswer();
};
elCheck.addEventListener('click', checkAnswer, false);
displayRandomQuestion();
Working jsfiddle
Doing it this way is shorter, cleaner and easier to maintain as well. Adding a new question/answer pair is as easy as adding another object to the array. No more copy/pasting if statements and other redundant code. In addition since there is only one place where each action is performed (questions/answers are displayed, the answer is checked, etc) if there is a bug with any of these features there is a single well defined place to look for the bug and you only have to fix it once instead of once for every question in your quiz.
The way I have abstracted lots of the work also makes it easier to extend the code in the future. For instance if you further abstract out the random number code:
getRandomIndex = function () {
return Math.floor(Math.random() * questions.length);
},
You can alter displayRandomQuestion so it will never repeat the same question twice in a row:
displayRandomQuestion = function () {
var index;
do {
index = getRandomIndex();
} while (index === currentIndex);
displayQuestion(index);
},
Or even ensure questions never repeat until all the questions have been asked:
askedIndexes = [],
displayRandomQuestion = function () {
var index;
do {
index = getRandomIndex();
} while (askedIndexes.indexOf(index) !== -1);
if (askedIndexes.length === questions.length - 1) {
askedIndexes = [];
}
askedIndexes.push(index);
displayQuestion(index);
},
Maybe I got killed here but I need to ask if this insane is possible through RegEx, see I have this Javascript/jQyery function for validates VAT number in Venezuela (RIF):
function(value) {
if (value === '') {
return true;
}
var $rif = value.val();
var $last_number = $rif.substr($rif.length - 1);
var $number = $rif.substr(0, 8);
$valid = /^([VEJPG]{1})([0-9]{9}$)/.test($rif_type + $rif);
if ($valid) {
if ($rif_type == "V") {
$sum = 1 * 4;
} else if ($rif_type == "E") {
$sum = 2 * 4;
} else if ($rif_type == "J") {
$sum = 3 * 4;
} else if ($rif_type == "P") {
$sum = 4 * 4;
} else if ($rif_type == "G") {
$sum = 5 * 4;
}
$n0 = $number.charAt(0) * 3;
$n1 = $number.charAt(1) * 2;
$n2 = $number.charAt(2) * 7;
$n3 = $number.charAt(3) * 6;
$n4 = $number.charAt(4) * 5;
$n5 = $number.charAt(5) * 4;
$n6 = $number.charAt(6) * 3;
$n7 = $number.charAt(7) * 2;
$sum += $n0 + $n1 + $n2 + $n3 + $n4 + $n5 + $n6 + $n7;
$mod = $sum % 11;
$last_val = 11 - $mod;
if ($last_val == 11 || $last_val == 10) {
$last_val = 0;
}
if ($last_number == $last_val) {
return true;
} else {
return false;
}
}
return false;
}
I'm asking if it's possible to write a RegEx to check the same and if so, how?
These are valid VAT numbers:
J298081775
J295809000
J298720620