Leveraging the outcome of a for loop in order to set a condition within an else if statement

How can I condition my third else if statement based on the result of a for loop?

        //If player clicks centre on first move go in corner square
        if (current[4] === playerToken && this.state.stepNumber === 1) {
          let move = cornerSquares[Math.floor(Math.random() * cornerSquares.length)];
          drawSquare(move);
        } 
        //If player clicks corner square on first move go in centre square
        else if (this.state.stepNumber === 1) {
          for (let i = 0; i < cornerSquares.length; i++){
            if (current[cornerSquares[i]] === playerToken) {
              drawSquare(4);
            }
          }
      }
        //If player or computer has 2 in a row, place in 3rd square to win or block
        else if (/*NEED HELP WITH THE CONDITION FOR THIS FOR LOOP*/) {
          for (let i = 0; i < twoInRow.length; i++) {
            const [a, b, c] = twoInRow[i];  
            if (current[a] && current[a] === current[b]) {
              drawSquare(c);
            }
          }
        }
        //Place in random empty square
        else {
         //code to randomly place x/o in random square
        }
      }

Answer №1

To streamline your code, consider utilizing the move variable to track where a move has been made or not yet, and incorporate it into your conditional statements:

let move = null;
// If player clicks center on first move, go in corner square
if (current[4] === playerToken && this.state.stepNumber === 1) {
    let move = cornerSquares[Math.floor(Math.random() * cornerSquares.length)];
} 
// If player clicks corner square on first move, go in center square
else if (this.state.stepNumber === 1) {
    for (let i = 0; i < cornerSquares.length; i++){
        if (current[cornerSquares[i]] === playerToken) {
            move = 4;
            break; // Save time by exiting loop early
        }
    }
}
// If either player or computer has 2 in a row, place in 3rd square to win or block
if (move === null) {
    for (let i = 0; i < twoInRow.length; i++) {
        const [a, b, c] = twoInRow[i];  
        if (current[a] && current[a] === current[b]) {
            move = c;
            break; // Save time by exiting loop early
        }
    }
}
// Place in random empty square if no other conditions met
if (move === null {
    // Add logic to randomly place x/o in an empty square here
    move = // your logic here
}
// Perform the determined move
drawSquare(move);

Answer №2

If you define c outside of the loop, you can move the loop to a separate function like this:

    let c = null;
    //If player clicks centre on first move go in corner square
    if (current[4] === playerToken && this.state.stepNumber === 1) {
      let move = cornerSquares[Math.floor(Math.random() * cornerSquares.length)];
      drawSquare(move);
    } 
    //If player clicks corner square on first move go in centre square
    else if (this.state.stepNumber === 1) {
      for (let i = 0; i < cornerSquares.length; i++){
        if (current[cornerSquares[i]] === playerToken) {
          drawSquare(4);
        }
      }
    }
    //If player or computer has 2 in a row, place in 3rd square to win or block

    //In JavaScript, you can assign inside an 'if' statement
    //An assignment evaluates to the value assigned
    //So we assign the result of 'hasTwoInRow' to 'c' and check if it's not null
    else if ((c = hasTwoInRow(twoInRow,current)) !== null) {
      drawSquare(c);
    }
    //Place in random empty square
    else {
     //Code to randomly place x/o in random square
    }
  }

  function hasTwoInRow(twoInRow,current) {
    for (let i = 0; i < twoInRow.length; i++) {
      const [a, b, c] = twoInRow[i];  
      if (current[a] && current[a] === current[b]) {
        return c;
      }
    return null;
  }

Answer №3

The result of my for loop should determine the third condition in the else if statement
=> Incorrect.

In an <b>if {} else ...</b> scenario, conditions are assessed simultaneously, with the first one that is true being executed. If you desire sequential evaluation of conditions, use <b>if {} if {} ...</b>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide on loading an external javascript file once a webpage is fully loaded, and incorporating a function from it

After the initial page load, I have a need to incorporate an external JavaScript file into an HTML file. This is necessary because a variable in this external JS file only updates after the HTML file has fully loaded. Additionally, I want to utilize the fu ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Resolving conflicts between Bootstrap and custom CSS transitions: A guide to identifying and fixing conflicting styles

I am currently working on implementing a custom CSS transition in my project that is based on Bootstrap 3. The setup consists of a simple flex container containing an input field and a select field. The functionality involves using jQuery to apply a .hidde ...

broadcast updated $rootScope

How do I update the $rootScope.$broadcast with a new value? Let's take a look at this code snippet: var test = "fisk"; if(angular.element(this).hasClass('monster')) { var monster_info = angular.element(this).find("img").attr("title"); ...

Bootstrap modal's offset returning blank value

One way to navigate to a specific element within a Bootstrap modal is by checking the offset of that particular element. If there are multiple divs within the modal, each with its own unique id (#row-1, #row-2, etc.), you can open the modal and input the f ...

Struggling to generate a fresh invoice in my project using React.js

I am fairly new to working with React and could really benefit from some assistance in understanding how to implement a new invoice feature within my current project. The Challenge: At present, I can easily create a new invoice as showcased in the images ...

Need help addressing a sliding page issue in my Upwork clone script using JavaScript

For those familiar with Upwork's UI, you may have noticed a small feature I implemented. When a user clicks on a freelance job offer, another page opens from the left side using transform: translate(120%) to transform: translate(0). The issue arises ...

Attempting to create a single function that can be utilized with numerous divs that share the same class in jQuery

Currently, I am working on creating a basic jquery gallery viewer. In my code, I have the following structure: <div class="photoset"> <img /> <img /> </div> <div class="photoset"> <img /> <img /> <i ...

How Angular pulls information from a JSON file using index identifiers

I am struggling to access the user item view from a json array called dealerLst. The complexity of the json is causing issues for me in accessing multiple users. Can someone guide me on how to access all children using angular or typescript? Additionally, ...

Issue: Request from a different origin blocked

I encountered an issue while working on a web project using the PlanGrid API. I am receiving a cross-domain request block error. var apiKey="API KEY"; var password="PASSWORD"; $.ajax({ url: "https://io.plangrid.com/projects", xhrFields: { ...

In AngularJS, I've created a collection of checkboxes with a submit button ready to go

One of my goals is to make the cancel button available only when at least one job is selected. Below is my HTML View <table> <tr ng-repeat="x in jobs" ng-class-odd="'odd'" ng-class-even="'even'"> <td style="widt ...

How can I use Angular to bind the text entered in an `input` within one `ng-repeat` `div` to another `div` within a different `ng-repeat`?

I am trying to create a dynamic Angular-based webpage where input tags are connected to h3 tags in separate DIVs. Below is the setup of my HTML page (as seen on Plunker): <!DOCTYPE html> <html> <head> <style type="text/css> ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...

Why does replacing <input> with <TextField> in Material-UI & React cause the form submission to fail?

Recently, I encountered an issue with my CRUD Todo app's form for adding tasks. Initially built with a basic HTML input and button setup, I decided to enhance the design using Material-UI components. After introducing <TextField> in place of th ...

Consider creating a distinct document for your "scripts"

Within my package.json configuration file, the "scripts" section contains numerous commands structured as shown below. "scripts" { "script1": "command example", "script2": "command example", "script3": "command example", "script4": "command exampl ...

Having trouble accessing data in Laravel and Vue JS views

I'm currently working on displaying table data in a view using Vue.js and Laravel. Here is what I have attempted so far: This is the comment controller: public function index() { $comment = Comment::Latest()->paginate(10); return new Comm ...

You are able to use a null type as an index in angular.ts(2538) error message occurred

onClick() { let obj = { fName: "ali", LName: "sarabi", age: "19", } let fieldName = prompt("field"); alert(obj[fieldName]); } I encountered an issue with the code above where alert(obj[fieldName] ...

Cross-site communication with Ajax using both POST and GET requests

As a beginner in JavaScript, I'm facing challenges with implementing ajax POST and GET requests. While I can successfully do it using Google Postman as shown here https://i.sstatic.net/Cegxj.pnghttps://i.sstatic.net/ovJT0.png, the problem arises when ...

When it comes to React, an unspoken truth is that undefined could potentially cause issues

I have been attempting to iterate through an array of data, following a guide without much success. The structure of the data file is as follows: import React, {Component} from 'react'; export default [ { id: 1, lk:593458, ld:18033, status: &ap ...

Error 404: This page seems to have gone missing. Django and react-router

Struggling to integrate reactjs and react-router (1.x) with my Django project. I'm finding it challenging to make everything work together seamlessly. For more details, you can check out the project on GitHub: https://github.com/liondancer/django-che ...