The 'IN' Operator in JavaScript

Recently, I embarked on a journey to learn the art of JavaScript, and my current project involves creating a Tic Tac Toe game. However, I've hit a roadblock with the IN statement, as it consistently returns True under the specified condition.

function getMove(index){
    key=parseInt(index);
    var temp;
    temp=moves;
    elem=document.getElementById(index);
    var valid_move=(key in temp);
    document.getElementById('warning').innerText=valid_move;`

The crux of the issue lies within the 5th statement of the function above: var valid_move=(key in temp);

No matter how I manipulate the value of index once it's occupied, the outcome invariably remains True:

var key;
var elem;
var moves=[1,2,3,4,5,6,7,8,9,10];
var score_x=0;
var score_o=0;

var X=true;
function getMove(index){
    key=parseInt(index);
    var temp;
    temp=moves;
    elem=document.getElementById(index);
    var valid_move=(key in temp);
    document.getElementById('warning').innerText=valid_move;

    if (X && valid_move){
        elem.innerText='X';
        elem.style.color='Crimson';
        moves[key-1]='occ';
        X=false;
        document.getElementById('head').innerText=temp;
    }else if(!X && valid_move){
        elem.innerText='O';
        elem.style.color='blue';
        moves[key-1]='occ';
        document.getElementById('head').innerText=temp;
        X=true;        
    }
    else {
        document.getElementById('warning').innerText='Already Occupied !'
    }
    var len;
    len=temp.length;
    if (len==1){
        document.write('GAME OVER');
    }
}

This is the whole code.

If you observe carefully, every time an index gets occupied, its value switches to occ to prevent players from placing moves at the same position twice (as expected in TIC TAC TOE). Nonetheless, I'm still able to place moves at the same spot more than once.

Your assistance would be greatly appreciated.

Answer №1

Modifying the value of a key does not erase the key itself. The focus should be on verifying the existence of the key and examining its current value, rather than eliminating it completely. When updating the value, it is crucial to assess the specific value associated with the key:

var valid_move = key in temp && temp[key] != 'occ';

This condition confirms both the presence of the key and ensures that its value is not equal to 'occ'.

Key versus Value

Within an array, keys and values maintain distinct roles. Each key within the array corresponds to a particular value. While "key" is not a reserved term, it holds significance within language specifications. The confusion often stems from failing to differentiate between the key itself and the value assigned to it. It is essential to recognize that although the key itself can be perceived as a value, the actual content it represents serves as a separate entity.

For example: someArray[0] = 1; In this context, 0 acts as the key, while 1 signifies the value associated with it. Despite the value alteration to 1 via moves[key]='occ';, the key remains constant at 0. The modification solely impacts the value held by the key.

Upon initializing an array, emphasis is placed on supplying it with values rather than explicitly defining keys. The automatic generation of 0-based indices effectively assigns keys to corresponding values across the array elements:

var moves = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

This declaration is functionally equivalent to:

var moves = {0:1, 1:2, 2:3, 3:4, 4:5, 5:6, 6:7, 7:8, 8:9, 9:10};

Demonstrating how the initialization allocates the range of keys (0 to 9) with respective values (1 to 10).

In the discussion regarding the "value of a key," the emphasis lies on evaluating the actual content represented by the key, rather than focusing on the key itself. This principle extends beyond Javascript and applies universally across various programming languages.

Answer №2

Your understanding of the key and value seems to be a bit confused due to the data format being unclear, with values closely resembling keys.

When using the in operator, it actually checks for the existence of the key within the object.

For instance, if you are working on an array like this:

var moves=[1,2,3,4,5,6,7,8,9,10];

Within the array moves, the value 1 is at index 0/key 0, and the value 10 is at index 9/key 9. So, even if you change moves[9] to 'occ', the key/index 9 still exists. Therefore, when you check 9 in moves, it will return true.

If you wish to use the in operator, consider using delete moves[key-1]; to remove the assignment instead of directly replacing it with a new value like moves[key-1] = 'occ';.

For more detailed information, refer to the documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

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

How to Transfer Deleted List Items from one Unordered List to another in Angular 9 using Event Binding

Greetings to all =) I've recently delved into Angular 9 and I'm really enjoying the component-based approach. To sharpen my skills in property and event binding, I embarked on a project involving building a deck with two lists. English isn't ...

Whoops! Unable to interpret properties from an undefined source while trying to retrieve 'get'

Every time I execute my program, I encounter the following error: Cannot read properties of undefined (reading 'get') TypeError: Cannot read properties of undefined (reading 'get') at Proxy.mounted (webpack-internal:///./node_module ...

Encountering installation issues with npm for bcrypt installation due to a

While working on an Express JS project, I encountered issues trying to install the bcrypt module for data authentication. Despite multiple attempts, I kept receiving the same errors. [email protected] install /media/iron/1d6c195f-2350-423c-a3f0-050 ...

ways to invoke javascript function on body loading

I'm struggling to invoke a JavaScript function when the body loads. Currently, I have the function call on a button but cannot get it to work when added to the body load event. HTML: <body onload="bodyload();"> JavaScript: function bodyload( ...

Express 4: The requested route was not found by the router

Encountering a peculiar issue - the initial route functions properly, but when trying the parameterized route, a 404 error is returned. const express = require('express'); const router = express.Router(); router.route('/') .get(fu ...

MariaDB not properly handling empty lists in JSON_ARRAY function

Encountering an issue in my MariaDB (version 10.3.18) when utilizing the JSON_ARRAY function. When my subqueries do not return any results, instead of an empty array, I receive an array containing 1 null result. Example: SELECT JSON_ARRAY() // -> [] d ...

Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here The project involves two lists - one containing pets and the other ...

Testing an asynchronous generator function in Jest using unit tests

I need help writing a unit test for a generator function where I am struggling to properly mock a read stream object (ReadStream). Here is the function I'm trying to test: public async *readChunks(file: string, chunkSize: number): AsyncIterableIter ...

What is the method for adding items to an Eigen array or matrix?

How can an element be added to an Eigen array or matrix? By utilizing STD vector, the push_back function can be used. vector<int> index; int random = 1 + (rand() % 5); for (int i = 0; i < random; i++) index.push_back(i+i); ...

Discovering the clicking actions on PDF elements within an HTML environment

I am currently working on developing a web application that involves rendering various pdf objects. My main goal is to be able to detect the position of a click inside the pdf container. However, it seems like the OnClick event is not functioning as expe ...

Having trouble displaying values from nested JSON in a datatable

Response from server : ["{\"CLIENT\":[{\"tranche\":\"1-4\",\"prix\":\"65.96\",\"currency\":\"E\"}],\"DISTRIBUTEUR\":[{\"tranche\":\"1-4\",\"prix\ ...

Steps for creating a Foundation 6 accordion

Can anyone assist me in creating a Foundation 6 accordion? I tried to follow the code from the documentation, but it's quite confusing. I seem to be missing something and can't figure out what. Here is the HTML code from the docs: <ul class= ...

Tips for passing a parameter (such as an ID) through a URL using ng-click to display a subdocument belonging to a particular user in

I am looking to retrieve specific user subdocument data on a separate page by passing the id parameter in a URL using ng-click in AngularJS. <tr ng-repeat="register in registerlist | filter:searchText"> <td>{{$index+1}}</td> <td&g ...

Replacing URLs in Typescript using Ionic 3 and Angular

Currently facing some difficulties getting this simple task to work... Here is the URL format I am dealing with: https://website.com/image{width}x{height}.jpg My objective is to replace the {width} and {height} placeholders. I attempted using this func ...

Showing information from asynchronous AsyncStorage.getItems in React Native

In my app, users have to validate their success on challenges by clicking a validation button which saves the "key":"value" pair of the challenge using this function: async function validate(challenge_nb) { try { await AsyncStorage.setItem(challenge_n ...

Initiate data extraction immediately upon the DOM being fully loaded using NightmareJS

Currently, I am utilizing nightmarejs and facing a challenge that I am struggling to resolve. After using the goto(URL) command, I then proceed to use the evaluate() command to execute specific operations on the webpage. However, I have noticed that while ...

Update database upon drag-and-drop using jQuery

I have a dataset (shown below) that undergoes sorting by 'section'. Each item is placed into a UL based on its section when the page loads. My goal is to automatically update the section in the database when a user drags an item to a different s ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...

Transform a text node into an HTML element with the help of JQuery

Consider this HTML snippet: <div> Lorem ipsum <span>dolor sit</span> amet <span>consectetur adipiscing elit</span> eiusmod tempor </div> To select the text nodes [Lorem ipsum, amet, eiusmod tempor], ...

Is there a way to make a picture fill the entire background?

Is there a way to make pictures expand across an entire page with different resolutions? I'm trying to achieve this effect but unsure how. Take a look at my current example: . ...