I am in the process of creating a calculator in javascript, and am trying to make a backspace. My initial thought was to use the .slice function, and it works, to a point. It works in the way that it takes a number off, but I am having trouble getting it to actually take off the number from the first value, if that makes any sense. It doesn't work on the first time, for example, if I type in 12, then use the backspace, then make the number 13 and do 13 + 6; it will come up with NaN. However if I do that same process again, it works as long as i use my clear button and not refresh the page. I have tried everything I can think of, bu't can't get it to work. Here is the code, sorry its a lot, but I figured it be better to have it all there. I am open to any suggestions, but prefer not to use jQuery, as I haven't yet learned a single thing about jQuery
Code:
//Variables
var xValue = 0;
var xValue2 = 0;
//Button Values
var plusButton = 0;
var subButton = 0;
var timesButton = 0;
var divideButton = 0;
var squaredButton = 0;
var powerButton = 0;
//Answers
var sum = 0;
var difference = 0;
var product = 0;
var quotent = 0;
var square = 0;
var power = 0;
//Functions
function add () {
if (plusButton >= 1) {
xValue2 = xValue;
xValue = "";
}
subButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
//alert(xValue);
}
function addFunction () {
sum = +xValue + +xValue2;
answer.innerHTML = sum;
}
function subtract () {
if (subButton >= 1) {
xValue2 = xValue;
xValue = "";
}
plusButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
}
function subtractFunction () {
difference = +xValue2 - +xValue1;
answer.innerHTML = difference;
}
function multiply () {
if(timesButton >= 1) {
temp = xValue2;
xValue2 = xValue;
xValue = "";
}
subButton = 0;
plusButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
}
function multiplyFunction () {
product = +xValue * +xValue2;
answer.innerHTML = product;
}
function divide () {
if(divideButton >= 1) {
temp = xValue2;
xValue2 = xValue;
xValue = "";
}
subButton = 0;
plusButton = 0;
timesButton = 0;
squaredButton = 0;
powerButton = 0;
}
function divideFunction () {
var quotent = +xValue / +xValue2;
answer.innerHTML = quotent;
}
function squared () {
subButton = 0;
plusButton = 0;
timesButton = 0;
divideButton = 0;
powerButton = 0;
}
function squaredFunction () {
square = Math.pow(xValue, 2);
answer.innerHTML = square;
}
function powerNum () {
if(powerButton >= 1) {
xValue2 = xValue;
xValue = "";
}
plusButton = 0;
subButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
}
function powerFunction () {
var power = Math.pow(xValue2, xValue);
answer.innerHTML = power;
}
function compute () {
if(plusButton >= 1) {
addFunction();
xValue = sum;
}
else if (subButton >= 1) {
subtractFunction();
xValue = difference;
}
else if (timesButton >= 1) {
multiplyFunction();
xValue = product;
}
else if (divideButton >= 1) {
divideFunction();
xValue = quotent;
}
else if (squaredButton >= 1) {
squaredFunction();
xValue = square;
}
else if (powerButton >= 1) {
powerFunction();
xValue2 = power;
}
xValue2 = 0;
plusButton = 0;
subButton = 0;
timesButton = 0;
divideButton = 0;
squaredButton = 0;
powerButton = 0;
}
function clearScreen() {
answer.innerHTML = "";
xValue = 0;
plusButton = 0;
xValue2 = 0;
temp = 0;
}
function backOne () {
var str = answer.innerHTML;
var res = str.slice(0, -1);
answer.innerHTML = res;
xValue = parseInt(res);
}
You can use substring on the current displayed value in the calculator and replace the current value with the substring of it. The substring would be (0, length - 1).
http://www.w3schools.com/jsref/jsref_substring.asp
EDIT: should be length - 1
Related
I am making a Conway Game of Life that it starts with a predefined board, I made that board through an two dimensional Array, have implemented the rules and they seem to be working, the problem is that the different generations just appear next to previous one without replacing it (see image [1])
image:
[![enter image description here][1]][1]
So, what i needed is to make the following generations replace the previous ones on the HTML display.
var gfg=new Array(10);
for (var COL=0; COL<gfg.length;COL++){
gfg[COL]=new Array(10);
}
run();
function run(){
board1();
rules();
}
function rules(){
for (var i=0; i<10;i++){
for(var j=0; j<10; j++){
const cell = gfg[i][j];
let numNeighbours = 0;
for (let x = -1; x < 2; x++) {
for (let y = -1; y < 2; y++) {
if (x === 0 && y === 0) {
continue;
}
var x_cell = i + x;
var y_cell = j + y;
if (x_cell > 0 && y_cell > 0 && x_cell <0 && y_cell <0) {
const currentNeighbour = 1;
numNeighbours=numNeighbours+currentNeighbour;
}
}
}
if (cell === 1 && numNeighbours < 2) {
gfg[i][j] = 0;
} else if (cell === 1 && numNeighbours > 3) {
gfg[i][j] = 0;
} else if (cell === 0 && numNeighbours === 3) {
gfg[i][j] = 1;
}
}
draw();
}
}
function draw(){
for (var i=0; i<10;i++){
for(var j=0; j<10; j++){
//Writes in HTML according to the coordinate value
if(gfg[i][j]===0){
document.write("◻");
}else if(gfg[i][j]===1){
document.write("◼");
}
}
document.write("<br>");
}
}
//predefined board
function board1() {
gfg[0][0] = 1;
gfg[0][1] = 0;
gfg[0][2] = 1;
gfg[0][3] = 0;
gfg[0][4] = 0;
gfg[0][5] = 1;
gfg[0][6] = 0;
gfg[0][7] = 0;
gfg[0][8] = 0;
gfg[0][9] = 1;
gfg[1][0] = 0;
gfg[1][1] = 0;
gfg[1][2] = 0;
gfg[1][3] = 0;
gfg[1][4] = 0;
gfg[1][5] = 0;
gfg[1][6] = 0;
gfg[1][7] = 1;
gfg[1][8] = 0;
gfg[1][9] = 0;
gfg[2][0] = 0;
gfg[2][1] = 0;
gfg[2][2] = 0;
gfg[2][3] = 1;
gfg[2][4] = 0;
gfg[2][5] = 1;
gfg[2][6] = 1;
gfg[2][7] = 0;
gfg[2][8] = 0;
gfg[2][9] = 0;
gfg[3][0] = 0;
gfg[3][1] = 0;
gfg[3][2] = 1;
gfg[3][3] = 0;
gfg[3][4] = 1;
gfg[3][5] = 0;
gfg[3][6] = 0;
gfg[3][7] = 0;
gfg[3][8] = 0;
gfg[3][9] = 1;
gfg[4][0] = 0;
gfg[4][1] = 0;
gfg[4][2] = 0;
gfg[4][3] = 0;
gfg[4][4] = 1;
gfg[4][5] = 0;
gfg[4][6] = 0;
gfg[4][7] = 0;
gfg[4][8] = 0;
gfg[4][9] = 0;
gfg[5][0] = 0;
gfg[5][1] = 1;
gfg[5][2] = 0;
gfg[5][3] = 0;
gfg[5][4] = 0;
gfg[5][5] = 0;
gfg[5][6] = 0;
gfg[5][7] = 0;
gfg[5][8] = 0;
gfg[5][9] = 0;
gfg[6][0] = 0;
gfg[6][1] = 0;
gfg[6][2] = 0;
gfg[6][3] = 0;
gfg[6][4] = 1;
gfg[6][5] = 0;
gfg[6][6] = 1;
gfg[6][7] = 0;
gfg[6][8] = 1;
gfg[6][9] = 0;
gfg[7][0] = 1;
gfg[7][1] = 0;
gfg[7][2] = 0;
gfg[7][3] = 1;
gfg[7][4] = 0;
gfg[7][5] = 0;
gfg[7][6] = 0;
gfg[7][7] = 1;
gfg[7][8] = 0;
gfg[7][9] = 0;
gfg[8][0] = 0;
gfg[8][1] = 0;
gfg[8][2] = 1;
gfg[8][3] = 0;
gfg[8][4] = 1;
gfg[8][5] = 0;
gfg[8][6] = 0;
gfg[8][7] = 0;
gfg[8][8] = 0;
gfg[8][9] = 0;
gfg[9][0] = 0;
gfg[9][1] = 1;
gfg[9][2] = 0;
gfg[9][3] = 0;
gfg[9][4] = 0;
gfg[9][5] = 0;
gfg[9][6] = 0;
gfg[9][7] = 0;
gfg[9][8] = 1;
gfg[9][9] = 0;
}
[1]: https://i.stack.imgur.com/ZKrFj.png
this is if you are using document.write()
All you will have to do is clear the container of the previous write with document.body.innerHTML = ""; this will clear your previous writes and then you can go through the loop again.
If you need to use html and javascript only canvas will still work as it is a built in html tag. However if you still wish to proceed with using html to display your cells then create a new div tag and give it an id e.g: id="life_container" then grab a reference to this tag when the page finishes loading and on every frame empty the div then go through your loop and fill it with your elements.
var container;
document.onload = function() {
container = document.getElementById('life_container');
}
// clear container
container.innerHtml = "";
// fill container
container.innerHtml += gfg[i][j] === 0 ? "◻" : "◼";
However I might suggest some improvements by using canvas instead of html to display your game of life. You can use P5 library, to run your loop and display it. You will need to add in extra calculation to figure out "where" to draw your cell on canvas but not much more.
Im using the code below to try and find the first repeating character in a sequence. When I run the code in my browser, and stop it in the console at the letterArray.forEach function, console log error says my inputs to forEach are undefined. But it seems to me like forEach should just be taking the inputs from letterArray one at a time, seeing if they equal one, and return the result. Anybody know why it says my forEach loop cant read the inputs from my letterArray?
function firstNotRepeatingCharacter(string) {
var letterArray = [];
letterArray['a'] = 0;
letterArray['b'] = 0;
letterArray['c'] = 0;
letterArray['d'] = 0;
letterArray['e'] = 0;
letterArray['f'] = 0;
letterArray['g'] = 0;
letterArray['h'] = 0;
letterArray['i'] = 0;
letterArray['j'] = 0;
letterArray['k'] = 0;
letterArray['l'] = 0;
letterArray['m'] = 0;
letterArray['n'] = 0;
letterArray['o'] = 0;
letterArray['p'] = 0;
letterArray['q'] = 0;
letterArray['r'] = 0;
letterArray['s'] = 0;
letterArray['t'] = 0;
letterArray['u'] = 0;
letterArray['v'] = 0;
letterArray['w'] = 0;
letterArray['x'] = 0;
letterArray['y'] = 0;
letterArray['z'] = 0;
for(var letter of string) {
letterArray[letter] = letterArray[letter] + 1;
}
letterArray.forEach(function(value, index, thearay) {
if (value == 1) {
console.log(index);
}
});
}
var tester = "abacabad";
firstNotRepeatingCharacter(tester);
The minimal changes to your code required are as follows (see the comments // ****** in the code)
function firstNotRepeatingCharacter(string) {
// *********** change to Object
var letterArray = {};
letterArray['a'] = 0;
letterArray['b'] = 0;
letterArray['c'] = 0;
letterArray['d'] = 0;
letterArray['e'] = 0;
letterArray['f'] = 0;
letterArray['g'] = 0;
letterArray['h'] = 0;
letterArray['i'] = 0;
letterArray['j'] = 0;
letterArray['k'] = 0;
letterArray['l'] = 0;
letterArray['m'] = 0;
letterArray['n'] = 0;
letterArray['o'] = 0;
letterArray['p'] = 0;
letterArray['q'] = 0;
letterArray['r'] = 0;
letterArray['s'] = 0;
letterArray['t'] = 0;
letterArray['u'] = 0;
letterArray['v'] = 0;
letterArray['w'] = 0;
letterArray['x'] = 0;
letterArray['y'] = 0;
letterArray['z'] = 0;
for(var letter of string) {
letterArray[letter] = letterArray[letter] + 1;
}
// *********** an object has no forEach,
// so, we now need to iterate through the keys
// (a,b,c ...) of the object,
// that's where Object.keys helps
Object.keys(letterArray).forEach(function(key, index, thearay) {
var value = letterArray[key]; //the value is letterArray[key]
if (value == 1) {
console.log(key);
}
});
}
var tester = "abacabad";
firstNotRepeatingCharacter(tester);
However, looking at the name of the function, I would expect
firstNotRepeatingCharacter("abacabad"); // c
firstNotRepeatingCharacter("abadacad"); // d
If so, the code would be far simpler
function firstNotRepeatingCharacter(string) {
for (let i = 0; i < string.length; i++) {
if (string.split(string[i]).length == 2) {
return string[i];
}
}
return null;
}
console.log(firstNotRepeatingCharacter("abacadab"));
console.log(firstNotRepeatingCharacter("abadacab"));
I am making a poker game with HTML CSS and Javascript. Right now, I am making the part of the program that actually deals the cards. I need to have an if statement inside another if statement. When it runs through, it generates a random number, then I have a list of if statements that see first if the card has been chosen, then I have another if statement inside of the first if statement to see if the card has been dealt. I don't know why it won't work. Can anyone help? Here is the code:
var yourchipsvar = 500;
var alchipsvar = 500;
var potvar = 0;
var whotodealto = 0;
yourchipsvar = Number(yourchipsvar);
alchips = Number(alchipsvar);
potvar = Number(potvar);
document.getElementById("yourchips").innerHTML = Number(yourchipsvar);
document.getElementById("alchips").innerHTML = Number(alchipsvar);
document.getElementById("pot").innerHTML = Number(potvar);
function bet() {
yourchipsvar = yourchipsvar - 5;
potvar = potvar + 5;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
function bet15() {
yourchipsvar = yourchipsvar - 15;
potvar = potvar + 15;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
function bet25() {
yourchipsvar = yourchipsvar - 25;
potvar = potvar + 25;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
function bet50() {
yourchipsvar = yourchipsvar - 50;
potvar = potvar + 50;
yourchipsvar = Number(yourchipsvar);
potvar = Number(potvar);
document.getElementById("pot").innerHTML = potvar;
document.getElementById("yourchips").innerHTML = yourchipsvar;
}
var aceofspades = 0;
var twoofspades = 0;
var threeofspades = 0;
var fourofspades = 0;
var fiveofspades = 0;
var cardinhand = 0;
function deal() {
if (whotodealto == 0) {
dealuser();
} else {
alert("dealtotheAI");
}
}
function dealuser() {
var cardinhand = Math.floor(Math.random() * 6);
if (cardinhand == 0) {
if (aceofspades == 0) {
alert("You got an ace of spades");
var aceofspades = 1;
}
}
if (cardinhand == 1) {
if (twoofspades == 0) {
alert("You got a two of spades");
var twoofspades = 1;
}
}
if (cardinhand == 2) {
if (threeofspades == 0) {
alert("You got a three of spades");
var threeofspades = 1;
}
}
if (cardinhand == 3) {
if (fourofspades == 0) {
alert("You got a four of spades");
var fourofspades = 1;
}
}
if (cardinhand == 4) {
if (fiveofspades == 0) {
alert("You got a five of spades");
var fiveofspades = 1;
}
}
}
You are creating two different local variables for each aceofspades, twoofspades, etc. This is because var means to create a local variable in the scope you are in. So the variables defined here:
var aceofspades = 0;
var twoofspades = 0;
var threeofspades = 0;
var fourofspades = 0;
var fiveofspades = 0;
var cardinhand = 0;
function deal() {
if(whotodealto==0){dealuser();} else{alert("dealtotheAI");}}
function dealuser() {
var cardinhand = Math.floor(Math.random()*6);
...
}
Are different from the ones you create here:
function dealuser() {
...
if(aceofspades==0){
alert("You got an ace of spades");
var aceofspades = 1;
}
In that case var aceofspades means you are creating a local variable in the dealuser() function. Simply set the value of your already created variable, this way you are not making a new one:
if(aceofspades==0) {
alert("You got an ace of spades");
aceofspades = 1;
}
I made a puzzle game in javascript. I have made objects to keep some attributes relevant to the each pazzle squares. I want to get the object id which is relevant to the onclick.(not the div id). How to get the specific object id relevant to the clicked div?
window.onload = function() {
createDivs();
objects();
random();
onclickeventHanlder(event);
};
var getId;
var x = 3;
var counting = 0;
var tileSize = 600 / x;
var array2 = [];
var object = [];
function createDivs() {
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var id = i + "" + j;
var element = document.createElement('div');
element.setAttribute("class", "pieces");
element.setAttribute("id", id);
element.style.width = 600 / x + "px";
element.style.height = 600 / x + "px";
element.style.margin = "0px auto";
element.style.overflow = "hidden";
element.setAttribute("onclick", "onclickeventHanlder(this)");
if (count > 0) { // to break row-wise
if (i == count && j == 0) {
element.style.clear = "both";
}
}
element.style.float = "left";
document.getElementById('puzzle-body').appendChild(element);
}
count++;
}
}
function objects(){
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var objName = new Object();
objName.position = -(j * tileSize) + "px" + " " + -(i * tileSize) + "px";
objName.divID = document.getElementById(i + "" + j);
objName.id = count;
if(count<x*x-1){
objName.state = true; // if image is there
}else{
objName.state = false; // if image isn't there
}
object[count] = objName;
count++;
}
}
}
function reset(){
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var obj = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj.position;
}
looping++;
}
}
}
function random(){
var array = [];
while (array.length < ((x * x) - 1)) {
var randomnumber = Math.floor(Math.random() * ((x * x) - 1));
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i] == randomnumber) {
found = true;
break;
}
}
if (!found) {
array[array.length] = randomnumber;
}
}
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
if (looping < x * x-1) {
var random = array[looping];
var obj = object[random];
var obj2 = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj2.position;
}
}
looping++;
}
}
}
function onclickeventHanlder(event) {
var pos = event;
}
This js is to create "lyricLine" and showing strings on random position of the page.
While creating an object of oLyricLine and calling drawText, it supposed to display each string of array lyricLines one by one until last line is shown. When last line is time-out, the timer should stop and the created div.lyricline should be deleted.
While different objects are created, (in this case LyricGen1 and LyricGen2) their timer should be ticking simultaneously.
But currently only timer of LyricGen2 is working.
Code is attached below.
<script src="jquery-min.js"></script>
<div id="container">
<div class="lyricline" id="0">
demo
</div>
</div>
<style>
body{
background: #000;
color: #fff;
font-family: sans-serif;
}
#container{
position: relative;
width: 100%;
height: 100%;
}
.lyricline{
position: absolute;
text-align: center;
}
</style>
<script>
var idarray = [];
//Object oLyricLine
function oLyricLine(obj){
this.lyricLines = [];
this.textSize = 30;
this.toppx = -1;
this.leftpx = -1;
this.unixtime = -1;
this.widthpx = -1;
this.colorhex = "#fff";
this.obj = obj;
}
oLyricLine.prototype.drawText = function(){
if (this.toppx != -1 && this.leftpx != -1 && this.unixtime != -1 && this.widthpx != -1){
var transitionInTime = 10;
var transitionOutTime = 10;
var tickfactor = 5;
$("#"+this.unixtime).css({
"color": this.colorhex,
"left": this.leftpx,
"top": this.toppx,
"width": this.widthpx,
"font-size":this.textSize
}).attr({"class":"lyricline","id":this.unixtime}).text(this.lyricLines[0]);
var tickCount = 0;
lyricLinesCount = 0;
var lyricLinesTick = [];
for (var i =0; i <= this.lyricLines.length - 1; i++) {
lyricLinesTick[i] = this.lyricLines[i].length * tickfactor;
if(i>0){lyricLinesTick[i]+=lyricLinesTick[i-1];}
};
var nLyricLines = this.lyricLines;
var nUnixtime = this.unixtime;
idarray[nUnixtime] = setInterval(function () {
tickCount += 1;
if (tickCount == lyricLinesTick[lyricLinesCount]){
lyricLinesCount +=1;
if(lyricLinesCount != lyricLinesTick.length){
$("#"+nUnixtime).text(nLyricLines[lyricLinesCount]);
}else{
$("#"+nUnixtime).remove();
clearInterval(idarray[nUnixtime]);
}
}
},100);
}
};
oLyricLine.prototype.widthGen = function() {
this.widthpx = maxWidth(this.lyricLines, this.textSize);
};
var unixtime1=Date.now();
$("#container").append($("<div></div>").attr("id",unixtime1));
var obj1=$("#"+unixtime1);
var LyricGen1 = new oLyricLine(obj1);
LyricGen1.lyricLines = ["gen1 line1","1.line2","1-------LINE#3"];
LyricGen1.textSize = 50;
LyricGen1.toppx = Math.floor(Math.random()*($(window).height()-LyricGen1.textSize));
LyricGen1.widthGen();
LyricGen1.leftpx = Math.floor(Math.random()*($(window).width()-parseInt(LyricGen1.widthpx)));
LyricGen1.unixtime = unixtime1;
LyricGen1.drawText();
$("#container").append($("<div></div>").attr("id","Datenow"));
var obj2=$("#Datenow");
var LyricGen2 = new oLyricLine(obj2);
LyricGen2.lyricLines = ["2.1","TWO=two","2........3","gen2 line number 4","2>>line5"];
LyricGen2.textSize = 80;
LyricGen2.toppx = Math.floor(Math.random()*($(window).height()-LyricGen1.textSize));
LyricGen2.widthGen();
LyricGen2.leftpx = Math.floor(Math.random()*($(window).width()-parseInt(LyricGen1.widthpx)));
LyricGen2.unixtime = "Datenow";
LyricGen2.drawText();
function strlen(str){ var len = 0; for (var i=0; i<str.length; i++) { var c = str.charCodeAt(i); if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { len++; } else { len+=2; } } return len; }
function maxWidth (lyricLines, textSize) {
var maxStringLength=0, maxStringId=-1;
for (var i = lyricLines.length - 1; i >= 0; i--) {
if (maxStringLength < strlen(lyricLines[i])){
maxStringLength = strlen(lyricLines[i]);
maxStringId = i;
};
};
$("#container").append($("<div></div>").css({
"background":"#fff",
"color":"#000",
"visibility":"hidden",
"font-size":textSize
}).attr({"class":"lyricline","id":"widgen"}).text(lyricLines[maxStringId]));
var maxPxLength = $("#widgen").css("width");
$("#widgen").remove();
return maxPxLength;
}
</script>
lyricLinesCount = 0;
You're missing a var here, making lyricLinesCount an implicit global variable. You want to have it local to each timer, though.