While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop.

Consider this straightforward code snippet:

this.filters['1','2','3'....];
for (let i = 0; i < this.filters.length; i++) {
      if (this.filters[i] === '2') {
        this.filters = new_value;
      }
    }

TSlint suggests converting it to for-of, but that doesn't support modification. An alternative like:

for (const [i, el] of this.filters.entries()) { 

triggers a TypeScript compilation warning: Type 'IterableIterator<T>' is not an array type. Using keys() feels redundant here.

Why does TSlint persist in complaining about this restriction on for(const i=0; ...)?

If we execute a similar block of code using for-of:

this.filters['1','2','3'....];
for (let f of this.filters) {
      if (f === '2') {
        f = new_value;
      }
    }

We'll notice that the array remains unaltered post-loop. However, things change when the context involves objects:

let filters = [{id:'1'},{id:'2'},{id:'3'}];
console.log(filters)
for (let f of filters) {
      if (f.id === '2') {
        f.id = 'toto';
      }
    }
console.log(filters)

Strangely enough, the object array gets modified after the loop! Any insights on why this happens would be appreciated.

I've tried looking for solutions to this problem, referencing a closed GitHub issue at https://github.com/palantir/tslint/pull/1813, but couldn't find a definitive resolution.

Answer №1

When dealing with strings, you encounter the following:

A string is initially assigned to f. Then a new value is reassigned to f: f === '2'. However, the original string in the array remains untouched.

On the other hand, when working with objects:

A reference to an object is assigned to f. The object is then modified: f.id = 'toto'. Because the array contains only references to objects, the modification reflects in the array.

This fundamentally highlights the distinction between variables of reference type and value type.

If you are encountering issues with

for (const [i, el] of this.filters.entries()) {
due to TypeScript settings, you can consider the following alternatives:

arr.forEach((entry, index) => arr[index] = ...);

or a less elegant solution:

for(entry of arr) {
    arr[arr.indexOf(entry)] = ...;
}

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

Error encountered with underscore template - Unforeseen SyntaxError: Unexpected token <

I encountered an error when attempting to load one of my underscore templates. It seems to be related to an issue in the for loop, which I suspect should be a .each loop, but I'm still trying to grasp its structure. Here is a snippet of my template: ...

Encountering ExpressionChangedAfterItHasBeenCheckedError in Angular 17 even after invoking detectChanges method

I'm encountering a minor problem with Angular and its change detection mechanism. I have created a simple form where additional input fields can be added dynamically. However, every time I click the add button, an ExpressionChangedAfterItHasBeenChecke ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

Adding a class to a div upon loading: A guide

Currently using the following script: $(document).ready(function() { $(".accept").change(function () { if ($(this).val() == "0") { $(".generateBtn").addClass("disable"); } else { $(".generateBtn").remove("dis ...

Issue with dropshadows in Chrome: Instead of applying the shadow effect to the graphic itself, it is mistakenly being added to the container

Having trouble adding a Gaussian drop shadow to an SVG path. The shadow is not applying correctly in Chrome - instead of just on the graphic, it's being added to the container. Works fine in ff though. Any suggestions on how to make this work properly ...

The concept of recursively exporting modules in Node.js modules

Looking for a way to recursively export all .hbs files in a NodeJS 14+ project main JS. I attempted the following: module.exports = () => ({ partial : __dirname + "/../partial/**.hbs", helper : __dirname + "/../helper/*.js" } ...

What could be causing the presence of a "strike" in my typescript code?

While transitioning my code from JavaScript to TypeScript for the first time, I noticed that some code has been struck out. Can someone explain why this is happening and what it signifies? How should I address this issue? Here's a screenshot as an exa ...

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...

Implement a concealed identification field with React-Admin within a React Native application

I'm currently working on incorporating the SimpleFormIterator from the React-Admin module in order to generate a list of child records within a parent record edit form. After setting up the SimpleFormIterator component with all the necessary details ...

What is the best way to hear an event emitted by a component?

I am trying to listen for an event in Chrome DevTools Vue, but I'm not sure how to target it. For a Root event, I typically use: this.$root.$on("note_id", (note_id) => (this.note_id = note_id)); But how do I address an event that origina ...

Updating information without the need for a page refresh

My project involves text boxes and drop-down menus where users input data, then click "generate" to combine the text from the boxes and display the result on the page. I'm struggling with clearing these results if the user clicks generate again, for ...

AngularJS: The 'myInputName' property is not defined and cannot be read

Encountering an error with AngularJS: https://i.sstatic.net/TBHem.png The issue is related to the titleInput TextBox name property: @Html.TextBox("titleInput", null, new { @placeholder = @T("Message title"), @class = "form-control", ng_model = "feed.fee ...

What is the best way to incorporate a line into a scene using three.js?

I am facing an issue with adding a line in three.js. When I call the addline function in my code, the line doesn't appear in the scene. I have tried to implement the MVC design pattern, but I am unsure where I went wrong. Thank you for any assistance ...

Angular Material: Enable Window Dragging Across Multiple Monitors

Exploring the usage of Angular Material Dialog or any other Popup Window Component. The functionality is mostly working as expected, with the exception of the last point. a) The original screen should not have a grey overlay, b) Users should be able to i ...

Is there a way to modify the parent component's state and pass it down to the child component as a prop efficiently?

I am facing an issue with a parent component that sets the score counter and passes it to the child component. There is a function in the parent component called resetBoard() which should reset the score counter back to 0 when triggered by a button click ...

Bootstrap-tour is incompatible with a row within a table structure

Is there a way to highlight a table row effectively? I've been struggling with it and tried using the fix mentioned in this bootstrap-tour issue here Check out this demonstration on jsFiddle: jsFiddle JAVASCRIPT $("#dialog").dialog(); var t = new ...

Resolving the "Error: Cannot update a React state on an unmounted component" issue

I encountered a console error while attempting to navigate to a new page within my web application. Here's the error message I received: Warning: A React state update was attempted on an unmounted component, which is essentially a no-op. However, t ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

Attempt to create a truncated text that spans two lines, with the truncation occurring at the beginning of the text

How can I truncate text on two lines with truncation at the beginning of the text? I want it to appear like this: ... to long for this div I haven't been able to find a solution. Does anyone have any suggestions? Thanks in advance! ...