After pasting the following code, my browser crashed. Why? - javascript

After pasting the following code, my browser crashed. I have absolutely no idea why. I am a new to Javascript.
Here is my code:
var randarray = new Array();
var l = 0;
var flag;
var numofpost = 5;
function randomposts(json) {
var total = parseInt(json.feed.openSearch$totalResults.$t, 10);
for (i = 0; i < numofpost;) {
flag = 0;
randarray.length = numofpost;
l = Math.floor(Math.random() * total);
for (j in randarray) {
if (l == randarray[j]) {
flag = 1;
}
}
if (flag == 0 && l != 0) {
randarray[i++] = l;
}
}
document.write('<ul class="rp-menu">');
for (n in randarray) {
var p = randarray[n];
var entry = json.feed.entry[p - 1];
for (k = 0; k < entry.link.length; k++) {
if (entry.link[k].rel == 'alternate') {
var item = "<li>" + "" + entry.title.$t + "</li>";
document.write(item);
}
}
}
document.write('</ul>');
}

The increment of i in your first for loop is behind a condition, so if it never resolves to true, you'll have an infinite loop

Related

recursive function returns the same value each time

So I have a checkers game, and I am trying to get it so that you can jump over multiple spaces. It works if you jump the max amount of spaces, but if you don't, say you can jump over two spaces, and you choose to jump over only one, it still removes both pieces even though you only jumped over one of the pieces. I think the problem has is inside the checkForJump() function, and it seems like every time the function is called, it returns the same array, any help would be appreciated.
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
Here is some of the other code, relating to that could also be the source of the problem
function jumpTile(tileID) {
this.tilesToRemove = [];
this.tileID = tileID;
};
let numBlackPieces = 12;
let numWhitePieces = 12;
let adjacentTileValues = [7, 9, -7, -9];
let availableSpaces = [
[],
[],
[],
[]
];
function checkValidSpace(buttonPressed, piece) {
// if button is adjacent to selectedbutton
if (buttonPressed == selectedButton + 7 || buttonPressed == selectedButton + 9 || buttonPressed == selectedButton - 9 || buttonPressed == selectedButton - 7) {
return true;
} else {
let valid = false;
// checks if there is a valid jump
checkForJump(selectedButton,[],true);
// foreach of the possible tiles, if the button pressed is one of them than remove all pieces in that tiles remove list
for (let i = 0; i < availableSpaces.length; i++) {
for (let j = 0; j < availableSpaces[i].length; j++) {
if (buttonPressed == availableSpaces[i][j].tileID) {
valid = true;
console.log("availableSpaces[" + i + j + "] is " + availableSpaces[i][j].tileID + "");
remove(availableSpaces[i][j].tilesToRemove);
return true;
}
}
}
if (valid == false)
return false;
}
}
function checkForJump(buttonSelected, remove, isRoot) {
if(isRoot)
{
clearAvailableMoves();
switchPiece();
}
let adjacentValue = 0;
let jumpNotValid = false;
let RemoveTiles = remove;
for (let i = 0; i < adjacentTileValues.length; i++) {
adjacentValue = adjacentTileValues[i];
if (board.value[adjacentValue + buttonSelected] == enemyPiece && board.value[buttonSelected + (adjacentValue * 2)] == empty) {
if (isSpaceAlreadyInArray(buttonSelected + adjacentValue * 2, i) == false) {
RemoveTiles.push(buttonSelected + adjacentValue);
let tile = new jumpTile(buttonSelected + (adjacentValue * 2));
RemoveTiles.push(buttonSelected + adjacentValue);
console.log("removeTiles" + RemoveTiles);
for (let k = 0; k < RemoveTiles.length; k++) {
tile.tilesToRemove.push(RemoveTiles[k]);
}
console.log("tile.tilesToRemove: " + tile.tilesToRemove);
availableSpaces[i].push(tile);
checkForJump(buttonSelected + (adjacentValue * 2), RemoveTiles,false);
console.log("available spaces = " + availableSpaces);
}
}
}
};
function isSpaceAlreadyInArray(spot, arrayIndex) {
let SpaceAlreadyInArray = false;
for (let j = 0; j < availableSpaces[arrayIndex].length; j++) {
if (availableSpaces[arrayIndex][j].tileID == spot) {
SpaceAlreadyInArray = true;
}
}
return SpaceAlreadyInArray;
}
function clearAvailableMoves() {
for (let i = 0; i < availableSpaces.length; i++) {
availableSpaces[i].pop();
}
}
function remove(removeList, button) {
for (let i = 0; i < removeList.length; i++) {
board.value[removeList[i]] = empty;
board.buttons[removeList[i]].textContent = empty;
if (piece == black) {
numBlackPieces--;
checkForWin(numBlackPieces);
} else if (piece == white) {
numWhitePieces--;
checkForWin(numWhitePieces);
}
}
clearAvailableMoves();
};

TypeError in JavaScript when setting the Y position

When running this code I currently getting the error "TypeError: Invalid value for y-coordinate. Make sure you are passing finite numbers to setPosition(x, y)." all of my functions do work are are declared properly. When I use a println and print out letYPos it prints out "NaN" but when I call the function again it prints out the correct value. Does anyone know how I can fix this or if there even is a way to fix this?
var count = 0;
var letYPos = 0;
var y = 3;
function testing()
{
var letXPos = 25;
letYPos += 75;
if (count == 6)
{
println("You have ran out of guesses, the correct anwser was: " + secretWord);
return;
}
var input = readLine("Enter your word: ");
if (input == null)
{
println("You have to enter a word! ");
return;
}
if (input.length != 5)
{
println("That is not a five letter word, please try again.");
return;
}
var x = 3;
for (var i = 0; i < input.length; i++)
{
if (input.includes(secretWord.charAt(i)))
{
var index = input.indexOf(secretWord.charAt(i));
}
if (index == 0) { yellow(3, y ) }
if (index == 1) { yellow(83, y ) }
if (index == 2) { yellow(163, y) }
if (index == 3) { yellow(243, y) }
if (index == 4) { yellow(323, y) } index = null;
}
for (var i = 0; i < input.length; i++)
{
if (input.charAt(i) == secretWord.charAt(i))
{
green(x, y);
}
x += 80;
}
y += 80;
for (var i = 0; i < input.length; i++)
{
for (var a = 0; a <= 5; a++)
{
var txt = new Text(input.charAt(a), font);
txt.setPosition(letXPos, letYPos);
add(txt);
letXPos += 80;
}
}
if (input == secretWord)
{
println("That's Correct, Congratulations!");
return;
}
count++;
setTimeout(testing, 100);
}

Not understood weird variable behavior in checkers game JavaScript

I'm programming a checkers game for a high school project. I have a weird variable behaviour and I can't figure out why it's happening. Let me show you the code:
var player = 1;
var lastClicked;
var wasClicked = false;
var isEmpty = new Array(8);
for (var i = 0; i < 8; i++) {
isEmpty[i] = new Array(8);
for (var j = 0; j < 8; j++) {
isEmpty[i][j] = true;
}
}
function CreateBoard() {
var board = document.createElement("table");
board.cellSpacing = 0;
for (var i = 0; i < 8; i++) {
var tr1 = document.createElement("tr");
for (var j = 0; j < 8; j++) {
var td1 = document.createElement("td");
td1.setAttribute("id", "td" + i + j);
td1.addEventListener("click", function () { CheckIandJForLater(i, j); });
if (i % 2 == 0) {
if (j % 2 == 0)
td1.style.backgroundColor = "beige";
else
td1.style.backgroundColor = "black";
}
else {
if (j % 2 == 0)
td1.style.backgroundColor = "black";
else
td1.style.backgroundColor = "beige";
}
tr1.appendChild(td1);
}
board.appendChild(tr1);
}
document.body.appendChild(board);
}
function CheckIandJForLater(i, j) { // A function which is meant to show the weird behavior, which prevents me from using function I want to use in the event listener
alert("Function i: " + i);
alert("Function j: " + j);
}
function DeployPieces() {
CreateBoard();
var pieceIndex = 1;
for (var i = 0; i < 8; i++) {
if (i < 3) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td1 = document.getElementById("td" + i + j);
var circle1 = document.createElement("span");
circle1.setAttribute("class", "redCircle");
circle1.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle1.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td1.appendChild(circle1);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td2 = document.getElementById("td" + i + j);
var circle2 = document.createElement("span");
circle2.setAttribute("class", "redCircle");
circle2.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle2.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td2.appendChild(circle2);
isEmpty[i][j] = false;
}
}
}
else if (i > 4) {
if (i % 2 == 0) {
for (var j = 1; j < 8; j += 2) {
var td3 = document.getElementById("td" + i + j);
var circle3 = document.createElement("span");
circle3.setAttribute("class", "whiteCircle");
circle3.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle3.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td3.appendChild(circle3);
isEmpty[i][j] = false;
}
}
else {
for (var j = 0; j < 8; j += 2) {
var td4 = document.getElementById("td" + i + j);
var circle4 = document.createElement("span");
circle4.setAttribute("class", "whiteCircle");
circle4.setAttribute("id", "circle" + i + j);
wasFilled = true;
circle4.setAttribute("onclick", "AlertToPressOnSquare(); lastClicked = this; wasClicked = true;");
td4.appendChild(circle4);
isEmpty[i][j] = false;
}
}
}
}
}
function AlertToPressOnSquare() {
alert("Player " + player + ", please press on the square to which you would like to move the piece");
if (player == 1)
player = 2;
else if (player == 2)
player = 1;
}
function MoveToSquare(i, j) { //The function I want to use in the td1 event listener
if (wasClicked && isEmpty[i][j]) {
var lastClickedId = lastClicked.getAttribute("id");
var lastClickedLocation = lastClickedId[6] + lastClickedId[7];
var v1 = parseInt(lastClickedId[6], 10);
var v2 = parseInt(lastClickedId[7], 10);
var tdFrom = document.getElementById("td" + lastClickedLocation);
var tdTo = document.getElementById("td" + i.toString() + j.toString());
if (lastClicked.getAttribute("class") == "whiteCircle") {
if (v1 == i - 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
else if (lastClicked.getAttribute("class") == "redCircle") {
if (v1 == i + 1 && (v2 == j - 1 || v2 == j + 1)) {
tdFrom.removeChild(lastClicked);
tdTo.appendChild(lastClicked);
}
}
alert("Player " + player + ", please press on the piece you would like to move");
wasClicked = false;
}
}
So, the weird behavior is as follows: Every time I click on a td in the table and run the CheckIandJForLater function, I get the value 8 for both i and j. They should not get these values, as i and j are supposed to be updated in the for loop. Moreover, they should never reach the value of 8, since both the loops run between 0 and 7.
It's also worth noting that if I put alert(i); and alert(j); regularly, without the CheckIAndJForLater function, their values are printed fine.
I really struglle in finding out how to solve this weird behavior. May someone help me? Thank you.
Why is that behavior happening? Is there a solution?

javascript Unexpected token else

Someone please help what is wrong in the following code. It is saying "Unexpected token else" while validating javascript code on Java Validate website - esprima.org
`
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
If (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
`
In Javascript there is no If statement. Javascript is a case-sensitive language Write it in the lower case - if. And also refactor your code, you have some unused variables.
The problem is that If should be lowercase.
The code should be like this:
function add1() {
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1; i <= size; i += 1) {
for (j = 1; j <= size; j += 1) {
if(i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
function add1()
{
var size = 8;
var widthOfGrid = size;
var lenthOfGrid = size;
var linenumber = 1;
for (i = 1 ; i<=size ; i += 1 )
{
for (j = 1 ; j<=size ; j += 1)
{
if (i % 2 === 0)
{
console.log(" " + "#");
}
else
{
console.log("#" + " ");
}
}
}
}
working code,you forget make your if in lowercase

Javascript: how to remove last comma in for-loop

How can I remove the last comma from this function.
for(var i = 0; i <= 100; i++) {
if(i % 2 === 0) {
div.innerHTML += l + ",";
}
else {
div.innerHTML += " ";
}
}
First, use arrays instead strings for sum strings, its faster.
Second:
var arr = [];
for (var i = 0 ;i <= 100; i+=2) arr.push(l);
dividedThree.innerHTML = arr.join(', ');
function loop {
for (var i = 0; i <= 100; i++) {
if (i % 2 === 0) {
dividedThree.innerHTML += l;
if (i < 100)
{
dividedThree.innerHTML += ",";
}
} else {
dividedThree.innerHTML += " ";
}
}
}
Try using and (&&) condition for 100 and show only i value for 100.
function loop() {
var dividedThree = document.getElementById('MY_ID');
for (var i = 0; i <= 100; i++) {
if (i % 2 === 0 && i !== 100) {
dividedThree.innerHTML += i + ", ";
} else if (i === 100) {
dividedThree.innerHTML += i;
} else {
dividedThree.innerHTML += " ";
}
}
}
loop();
<p id="MY_ID">
<p>
does this version work for you?
function loop() {
var data = '';
for (var i = 0; i <= 49; i++) {
data += l + ',' + ' ';
}
data += l;
dividedThree.innerHTML = data;
}
What are you trying to do? where does 'l' come from?

Categories