JavaScript Object Key is not being assigned to variable? - javascript

I am trying to assign the value of boxSpaces[0] to the variable result in the function decalreWinner() but the assignment is not taking place.
function assignSpace(mark, box) {
const image = document.createElement("img");
const src = mark === "x" ? X_IMAGE_URL : O_IMAGE_URL;
image.src = src;
box.appendChild(image);
box.removeEventListener("click", changeToX);
const id = parseInt(box.dataset.id);
boxSpaces[id] = mark;
}
function isGameOver() {
const length = emptyBoxes.length;
if (length <= 0) {
declareWinner();
return true;
} else {
false;
}
}
function declareWinner() {
const result = "";
if (boxSpaces["0"] === boxSpaces["1"] && boxSpaces["1"] === boxSpaces["2"]) {
result = boxSpaces["0"];
console.log(result);
}
return result;
}

You are using const to declare a variable and you are tring to update it which is not possible. change it to let or var
function declareWinner() {
let result = ""; //change it to let or var
if (boxSpaces["0"] === boxSpaces["1"] && boxSpaces["1"] === boxSpaces["2"]) {
result = boxSpaces["0"];
console.log(result);
}
return result;
}

Related

Function not returning properly when set to a variable but is when console.logged

The problem is in this function:
function minimax(newBoard,player, depth = 0) {
const availableSpots = emptySquares();
// console.log(availableSpots)
// console.log((checkGameStatus(newBoard,player) ? 'true' : 'false'))
let score = {};
if (checkGameStatus(newBoard, computerSymbol)) {
console.log("Are we hitting here? 1")
// console.log((onCheckWin(newBoard) === false))
// console.log(newBoard,"o")
score = { "score": (-100 + depth)}
return score
} else if (checkGameStatus(newBoard, playerSymbol)) {
console.log("Are we hitting here? 2")
// console.log(checkGameStatus(newBoard))
// console.log(newBoard,"o")
score = { "score": (100 - depth)}
return score
} else if (availableSpots.length === 0) {
console.log("Are we hitting here? 3")
score = { "score": 0 }
return score
}
let moves = [];
for (let i=0; i<availableSpots.length; i++) {
let move = {};
move.index = newBoard[availableSpots[i]];
newBoard[availableSpots[i]] = player;
console.table(newBoard)
if (player === computerSymbol) {
let result = minimax(newBoard, playerSymbol , depth++);
console.log(newBoard,"first");
console.log(result)
move.score = result["score"];
} else {
let result = minimax(newBoard, computerSymbol, (depth + 1));
console.log(newBoard,"first");
move.score = result.score;
}
console.log(moves,move)
newBoard[availableSpots[i]] = move.index;
moves.push(move);
console.log(moves,move)
} // end of for look
let bestMove;
if (player === computerSymbol) {
let bestScore = -10000;
for (let i=0; i<moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
// console.log(bestMove)
}
// end of for loop
}
if (player === playerSymbol) {
let bestScore = 10000;
for (let i=0; i<moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
// console.log(bestMove)
}
}
}
}
return moves[bestMove];
}
When I console.log the function inside of it, it returns an object, but when I set that function call to "result" like here:
if (player === computerSymbol) {
let result = minimax(newBoard, playerSymbol , depth++);
console.log(newBoard,"first");
console.log(result)
move.score = result["score"];
I get undefined as the result and that I can't access property of undefined. Also, I seem to have a problem with my minimax algorithm where it's just constantly choosing the next open square. This might be because I am only using an empty board at the moment. I can add more code if need be, but it seems to me that the problem exists inside the function and not from one of my external or helper functions

JS Promise Ignored (not sure)

I am working on an alert-similar function in javascript, and I got in trouble.
The code of the first function (prepBkCrt) looks like this:
function prepBkCrt() {
event.preventDefault();
crtBkMnl = true;
crtBkCnl = false;
const url = crtBkTab.querySelector("#url");
const name = crtBkTab.querySelector("#name");
if (name.value.length >= 17) {
poper("Bookmark","I will pass this part",true).then((response) => {
if (response === false) {
crtBkCnl = true;
hideBkTab();
return;
}
});
}
addBookmark(url.value,name.value);
if (crtBkCnl === false) {
poper("Bookmark","Bookmark successfully created!",false);
}
url.value = "";
name.value = "";
}
and the second function looks like this:
function poper(headerTxt, descTxt, option) {
return new Promise((resolve, reject) => {
const poper = document.querySelector("#poper");
const header = poper.querySelector("h2");
const buttonDiv = poper.querySelector("div");
const desc = poper.querySelector("span");
header.innerText = headerTxt;
desc.innerHTML = descTxt;
const yBtn = buttonDiv.querySelectorAll("button")[0];
yBtn.addEventListener("click", (event) => {poper.style.transform = "translateY(-300px)"; resolve(true);});
const nBtn = buttonDiv.querySelectorAll("button")[1];
nBtn.addEventListener("click", (event) => {poper.style.transform = "translateY(-300px)"; resolve(false);});
if (option === false) {
nBtn.style.display = "none";
} else {
nBtn.style.display = "block";
}
poper.style.transform = "none";
setTimeout(() => {poper.style.transform = "translateY(-300px)"; resolve(false);},10000);
});
}
This used to work well on other code, but it seems to not work on this javascript file. I've checked that it does run the first poper function in prepBkCrt function, which is the problem. The expected behavior is if the name.value's length is over 17, it should run poper function (it should work like this, and run this one, but the code only runs the second image. What's the problem?
You seem to be looking for an else statement. The return inside the .then() callback does not break from prepBkCrt.
function prepBkCrt() {
event.preventDefault();
crtBkMnl = true;
crtBkCnl = false;
const url = crtBkTab.querySelector("#url");
const name = crtBkTab.querySelector("#name");
if (name.value.length >= 17) {
poper("Bookmark","I will pass this part",true).then(response => {
if (response === false) {
crtBkCnl = true;
hideBkTab();
}
});
} else {
addBookmark(url.value,name.value);
poper("Bookmark","Bookmark successfully created!",false);
url.value = "";
name.value = "";
}
}

How to compare two variables and set a value of a third variable

I have this function I can't seem to get to work. I want it to compare two variables and set the value of a third variable.
var win_lose;
var this_roll = $('#past')[0].childNodes[9].textContent;
var last_roll = $('#past')[0].childNodes[9].textContent;
function compare() {
if (!(this_roll == last_roll)) {
win_lose = 'lose';
} else {
win_lose = 'win';
}
console.log(win_lose);
}
Did you actually call the function?
var this_roll = $('#past')[0].childNodes[9].textContent;
var last_roll = $('#past')[0].childNodes[9].textContent;
function compare(this_roll, last_roll) {
var win_lose; //added new variable here
if (this_roll != last_roll) {
win_lose = 'lose';
} else {
win_lose = 'win';
}
return win_lose;
}
var res = compare(this_roll, last_roll);
console.log(res);
I also rewrote your if statement, no need to check for equality then invert.
I would also pass parameters in to a function as I have.

How does Javascript evaluate the right parenthesis?

I'm working on a calculator that takes an expression such as (5+4) and evaluates it by passing the buttons pressed to an array, and then building a parse tree from the data in the array.
What's interesting/strange, is that my code won't push the value of the right parenthesis to the array. Here is my code, could someone help me out?
The console.log activeButton shows that is the value of the button being pressed, but even when I placed calcArray.push() outside the if statements it would not push ) to an array.
$(document).ready(function(){
var calcArray = new Array();
$("input").click(function(){
var activeButton = this.value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
});
});
The BuildTree code:
function BinaryTree(root) {
this.root = root;
this.activeNode = root;
}
function Node(element){
this.element = element;
this.parent;
this.rightChild;
this.leftChild;
this.setLeft = function(node){
this.leftChild = node;
node.parent = this;
};
this.setRight = function(node){
this.rightChild = node;
node.parent = this;
};
}
//methods
var buildTree = function(array)
{
var tree = new BinaryTree(new Node(null));
for(var i = 0; i < array.length; i++)
{
var newNode = new Node(array[i]);
if(array[i] == "(")
{
newNode.element = null;
tree.activeNode.setLeft(newNode);
tree.activeNode = newNode;
}
else if(array[i] == "+" || array[i] == "-" || array[i] == "/" || array[i] == "*")
{
tree.activeNode.element = newNode.element;
tree.activeNode.setRight(new Node(null));
tree.activeNode = tree.activeNode.rightChild;
}
else if(array[i] == ")")
{
if(tree.activeNode.parent == null)
{
;
}
else
{
tree.activeNode = tree.activeNode.parent;
tree.root = tree.activeNode;
}
}
else
{
tree.activeNode.element = newNode.element;
tree.activeNode = tree.activeNode.parent;
}
}
return tree.activeNode;
}
var evaluate = function(node){
var newNode1, newNode2;
newNode1 = new Node(null);
newNode1.parent = node;
newNode2 = new Node(null);
newNode2.parent = node;
if(node.leftChild == null && node.rightChild == null)
return node.element;
else{
newNode1.element = evaluate(node.leftChild);
newNode2.element = evaluate(node.rightChild);
if(newNode1.parent.element == "+")
{
return Number(newNode1.element) + Number(newNode2.element);
}
if(newNode1.parent.element == "-")
{
return newNode1.element - newNode2.element;
}
if(newNode1.parent.element == "*")
{
return newNode1.element * newNode2.element;
}
else
{
return newNode1.element / newNode2.element;
}
}
};
I just tried this out using your code and it worked fine passing the value as a string:
function pushButton (value) {
var activeButton = value;
console.log(activeButton);
if(!isNaN(activeButton))
{
calcArray.push(parseInt(activeButton));
console.log(calcArray);
}
else if(activeButton === "=")
{
evaluate(buildTree(calcArray));
calcArray = [];
}
else
{
calcArray.push(activeButton);
}
};
You aren't ever printing out the array in the last case (which is where the right paren would go), so are you sure it's not on the array and you just aren't seeing the visual feedback?
If so, we need to see more of your code. Try and setup a jsfiddle.

how to change javascript function to ActionScript 3?

anybody can help me to change that javascript function to AS3?
thanks :)
function parseURLtoVars(strLocation){
var rArray = new Array();
var key;
var urlString = new String(strLocation);
if (urlString.search(/\?/)>-1){
var qArray = urlString.split('?')[1].split('&');
if (qArray.length > 0){
for (key in qArray){
var arVal = qArray[key].split('=');
if (arVal.length ==2){
rArray[arVal[0]] = arVal[1];
} else {
continue;
}
}
return rArray;
} else {
return false;
}
}
return false;
}
How about
private function parseURLtoVars(strLocation:String):*
{
var rArray:Array = new Array();
var key:String;
var urlString:String = new String(strLocation);
if (urlString.search(/\?/)>-1){
var qArray:Array = urlString.split('?')[1].split('&');
if (qArray.length > 0){
for (key in qArray){
var arVal:Array = qArray[key].split('=');
if (arVal.length ==2){
rArray[arVal[0]] = arVal[1];
} else {
continue;
}
}
return rArray;
} else {
return false;
}
}
return false;
}
this returns params as an object, to return a boolean should be a simple edit.
function getParams(documentRoot):Object
{
try {
var params:Object = LoaderInfo(documentRoot.loaderInfo).parameters;
var pairs:Object = {};
var key:String;
for(key in params) {
pairs.key = String(params.key);
}
} catch(e:Error) {
return {};
}
return params;
}
I believe you just have to add type definitions to your function and variables.
So:
function parseURLtoVars(strLocation):Array
{
var rArray:Array = new Array();
var urlString:String = new String(strLocation);
...
for(var key:String in qArray)
...
return rArray;
} else {
return null;
}
}
return null;
}
I set the return of false to be nulls, but you can change your function return type to Object so you can return anything out of it, but I assumed you wanted an array to be returned.
It's not exactly what you asked, but in AS 3 I think there's an easier way:
import flash.net.URLVariables;
private function parseURLtoVars(strLocation:String):URLVariables {
strLocation = strLocation.indexOf("?") != -1 ? strLocation.split("?")[1] : strLocation;
return new URLVariables(strLocation);
}
And you could use it like this:
var testUrl:String = "test.php?key=value&key2=another_value";
var urlVars:URLVariables = parseURLtoVars(testUrl);
for(var k:String in urlVars) {
trace(k + " = " + urlVars[k]);
}

Categories

Resources