I pass an array by reference to another class, but it doesn’t get modified there [duplicate]

I have a problem with a web app I’m creating. In short, I want to pass an array by reference, so that change in a module will affect the array in the main class. The way I do it is:

  1. I send the array as a function parameter and assign it in the module
  2. I trigger the change in the main class, and the array is updated in the module
  3. When I update the array in the module, it is not updated in the main class.

I don’t understand it, array should be passed by reference, and apparently it is as the change works one way, but not the other. I log the values on both sides and see that it works. It’s driving me nuts…

Code boils down to this, these are the only places where arrays are affected.

Main class:

import { build } from "Module.js";

let usedRelations = [];

window.onload = function () {
build(usedRelations);
}

function addNewRelation(relationId) {
let rel = {}; // instantiating relation object here
usedRelation.push(rel); // it affects the array in the module class
}

Module:

let relationsArray;

export function build(usedRelations) {
relationsArray = usedRelations; 
}

function deleteUnsavedRelation(usedRelation) {

//relationsArray is filtered properly, but usedRelations from main class remain unchanged
relationsArray = relationsArray.filter(x => x.relationId != usedRelation.relationId); 
}

trublle with component in React

I had a problem exporting NavBottom and I don’t understand why the problem is that when I insert it into a component it knocks out an error, but the import and export are correct. Maybe there are nuances when using TypeScript, I recently started using it. I will be glad for any answer to my problem. Maybe I must “open” do object ?

import React, { useState } from 'react';
const styled = require('styled-components');
import {NavBottom} from './NavBottom';  

const BurgerMenu = () => {

  const [open, setOpen] = useState(false)

  const StyledBurger = styled.div`
  width: 2rem;
  height: 16px;
  margin-top:16px;
  margin-left: 19px;
  position: fixed;
  z-index: 20;
  display: none;
    display: flex;
    justify-content: space-around;
    flex-flow: column nowrap;
  div {
    width: 18px;
    height: 2px;
    background-color: #fff;
    border-radius: 10px;
    transform-origin: 1px;
    transition: all 0.3s linear;
    &:nth-child(1) {
      transform: ${open ? 'rotate(45deg)' : 'rotate(0)'};
    }
    &:nth-child(2) {
      transform: ${open ? 'translateX(100%)' : 'translateX(0)'};
      opacity: ${open ? 0 : 1};
    }
    &:nth-child(3) {
      transform: ${open ? 'rotate(-45deg)' : 'rotate(0)'};
    }
  }
`;

interface Props {
  open: boolean;
}
  
  return (
    <>
      <StyledBurger open={open} onClick={() => setOpen(!open)}>
        <div />
        <div />
        <div />
      </StyledBurger>
      <NavBottom open={open} />
    </>
  )
}

export {BurgerMenu};

My ‘AutoType’ function to type words automatically DOESN’T WORK

Details

Its a simple code. It gets the words in all .auto-type elements as input, then
type them automatically.

Here’s the CodePen : https://codepen.io/akolad/pen/zYPoEWd

Codes

  • javascript
    window.onload = () => {
        let elements = document.getElementsByClassName("auto-type");
        for (element of elements) {
            const text = element.innerHTML.toString();
            let charIndex = 0;
            const typing = () => {
                element.innerHTML += text.charAt(charIndex);
                if (charIndex < text.length) {
                    setTimeout(typing, 100);
                    charIndex++;
                }
            };
        }
    };
    
  • html (body)
    <body>
        <span class="auto-type code">hello!</span>
        <br />
        <span class="auto-type code">some text</span>
        <br />
        <div class="auto-type">some other text</div>
        <span class="auto-type code">here is a better text</span>
    
        <!-- js file: -->
        <script type="text/javascript" src="AutoType.js"></script>
    </body>
    

Problem

actually, js codes doesn’t work. and console is empty(no errors).
where’s the problem?

Stuck with creating a vector using HTML/CSS/JS

I want to create the specific pattern shown in the picture below. I have been brainstorming on the internet for a while now and can’t find a way to do it. This is like a connecting dots pattern where I want my page to show the bottom circle first then the dotted line leads to the next circle and then it goes on and on. But I am not sure how to implement it. If someone can help me with this would be of great help.

Image of the snippet I want

JS: No contents in array from parent class

I am using two classes in javascript.

class Challenge and class Modules, that extends Challenge.

in Challenge i have this constructor:

constructor() {
    this.handles = [];
}

and this method:

bla() {

    let elmnts = document.querySelectorAll("p"); // 5x
    
        for(let i=0; i < elmnts.length; i++) {
        
            let elmnt = elmnts[i];
            this.handles[elmnt['id']] = elmnt; // saves the handles to each element in separate array for later use
        
        }

}

in the child Class i am trying to use this “this.handles” array, but it is always empty.

It is not “undefined” but it is an empty array as i defined it in the constructor. its like the entries have never been set… but they are (as console.log() shows, when i insert it directly after the for()-loop)

console.log(this.handles); // --> []

Why does this happen?

where does “this” refer to? (javascript30 –Day10 by Wes Bos)

First of all, I’m a Japanese beginner web devlopment learner.
So, My English might be weird and I don’t have enough knowledge about programming.
I’m taking a course called javascript30 that focuses on various usage of vanilla JS and
I’m currently making a scheme to check the multiple checkboxes by pushing shift button and clicking it(if my explanation doesn’t make scence, please copy and paste the source code below)

Accornig to source code, I gotta change the boolean of “inBetween” by setting if sentence.
I can understand what he does but I can’t understand that where does “this” of “checkbox === this” refer to?
Why writing the code like “checkbox === this” means that it checks if check box is checked?
And I also struggle to catch the meaning of”let lastChecked“.
I understand “let lastChecked” is the key to check if it is the last checkbox that was checked by user, but why he set the value of “lastChecked” like “let lastChecked = this“?
Sorry for long sentence and poor English.
I’ll be happy if someone explain it.
I’ll paste the source code below.

source code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Hold Shift to Check Multiple Checkboxes</title>
</head>
<body>
  <style>

    html {
      font-family: sans-serif;
      background: #ffc600;
    }

    .inbox {
      max-width: 400px;
      margin: 50px auto;
      background: white;
      border-radius: 5px;
      box-shadow: 10px 10px 0 rgba(5, 5, 5, 0.1);
    }

    .item {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #F1F1F1;
    }

    .item:last-child {
      border-bottom: 0;
    }


    input:checked + p {
      background: #F9F9F9;
      text-decoration: line-through;
    }

    input[type="checkbox"] {
      margin: 20px;
    }

    p {
      margin: 0;
      padding: 20px;
      transition: background 0.2s;
      flex: 1;
      font-family: 'helvetica neue';
      font-size: 20px;
      font-weight: 200;
      border-left: 1px solid #D1E2FF;
    }
  </style>


  <div class="inbox">
    <div class="item">
      <input type="checkbox">
      <p>This is an inbox layout.</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Check one item</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Hold down your Shift key</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Check a lower item</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Everything in between should also be set to checked</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Try do it without any libraries</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Just regular JavaScript</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Good Luck!</p>
    </div>
    <div class="item">
      <input type="checkbox">
      <p>Don't forget to tweet your result!</p>
    </div>
  </div>

<script>
const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');

let lastChecked;

function handleCheck(e) {
  // Check if they had the shift key down
  // AND check that they are checking it
  let inBetween = false;
  if (e.shiftKey && this.checked) {
    // go ahead and do what we please
    // loop over every single checkbox
    checkboxes.forEach(checkbox => {
      console.log(checkbox);
      if (checkbox === this || checkbox === lastChecked) {
        inBetween = !inBetween;
        console.log('Starting to check them in between!');
      }

      if (inBetween) {
        checkbox.checked = true;
      }
    });
  }
  lastChecked = this;
  
}

checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));
</script>
</body>
</html>

2D custom shape to 3d model

for my school project i want to make a drawing app in canvas with multiple fuctions, lines, shapes, etc., but all in black color so shapes cover each other. I have already made that, but here it stops. After drawing i want to extrude that custom shape from canvas and make 3D model so i can export it to .stl and 3d print it. Do you have any ideas how i can do that. I was thinking about using three.js. This app will be used to draw cake-topper or any other shape you want to 3d print. Thanks for replaying.

Are service workers suitable to cache assets from other pages than the one active?

I’m considering to learn and use service workers to speed up a website I’m currently developing. It’s a full custom wordpress site, theme made from zero by me.

I’ve got some big js and css assets to manage. In detail:

  • one big ‘shared’ css, and the a lot of page-specific smaller ones

  • one big ‘shared’ js, and the a lot of page-specific smaller ones

  • another big ‘semi-shared’ js, which I use only for some pages (where I built a couple of mini Vue apps)

In particular, I’m interested in caching the last one, the ‘semi-shared’, in background while and when the user is navigating other pages that don’t use it, so that when users evcentually come to the vue mini apps, js are already loaded.

So basically, example, while I’m visiting /home or other pages, service workers should load the assets needed for /vue-app. Are the service workers suitable for this?

can we implement a way where we could upload files in variable number of fields by clicking addfile button using multer?

I actually tried to implement this feature but req.files and req.file are showing up undefined every time.
what i did actually is implemented a button on which whenever we click,a new input file field will be created and gets clicked automatically so that we could select files.In addition I also had created an anchor tag via which i will be passing the field names(file1,file2 etc) to the multer.Now when we click on the submit button,two events will happen in sequence,first of all the fieldname will be appended to the href of the anchor tag and gets clicked automatically and after that the form gets submitted.
Now on backend side the controller for that anchor tag create a new array (say ‘arr’) and pass it inside the
multer({storage:storage}).fields(arr) and saving this middleware in some variable say ‘mul’.Now the form submission takes place and its controller will be using the multer middleware which was present
inside the variable ‘mul’,but here req. files and req.file is showing up undefined.

how to keep session enabled in firebase/auth js?

When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn’t work.
This is my code

const iniciarSesion = (e) => {
    const auth = getAuth();
    setPersistence(auth, browserLocalPersistence)
    .then(() => {
        signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                setVentana("Tienda")
            })
            .catch((error) => {
                console.log(error)
            });
    })
}
const registar = (e) => {
    const auth = getAuth();
    createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
            setVentana("Tienda")
        })
        .catch((error) => {
            console.error(error)
        });
}

android mute music on first button click and run it again on second button click

I have a simple app that has three buttons, you can increase a number using pulse button and decrease it using minus button and if this number become bigger than 10 the sound will start and if the number become less than 10 the sound will be paused.

and there is a third button to mute the sound that started from increasing and decreasing the number and run the sound when you click the same button again.
this mute button should mute the sound on the first click and on the and run it again on second click.

my code is working fine but I had a little problem which is when I click the third button again the sound doesn’t start it only mute the sound on the first click .

here my code for the three buttons:

    mp = MediaPlayer.create(this, R.raw.gg);

    final ImageButton btn3= (ImageButton) findViewById(R.id.imgBtnSound);

     btn3.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            clicked = true;

            if(clicked) {
                mp.setLooping(false);
                mp.pause();
                clicked = false;

            } else  if(clicked == false){
                mp.setLooping(true);
                mp.start();
                clicked = true;
            }


        }
    });



    tv = (TextView) findViewById(R.id.TextNumber);

    ImageButton btn1= (ImageButton) findViewById(R.id.imgBtnUp);
    ImageButton btn2= (ImageButton) findViewById(R.id.imgBtnDown);

    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            result = result + 1;
            tv.setText("" + result);

            //check if need to play or not
            boolean needToPlay = result > 10;

            // if need to play, play when it's already not playing
            if (needToPlay && !mp.isPlaying()) {
                mp.setLooping(true);
                mp.start();
            }

        }
    });


    btn2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            result = result - 1;

            tv.setText("" + result);

            //check if need to play or not
            boolean needToPause = result <= 10;

            // if need to pause then pause only if it's playing
            if (needToPause && mp.isPlaying()) {
                mp.setLooping(false);
                mp.pause();
            }
        }
    });

HTML5 make empty div full viewport size

I’m trying to create an EMPTY div that takes up 100% of the viewport and that moves with the viewport (or position: fixed)

The background reason for this is so I can use the div as a full page tooltip that shows the mouse x and y positions and the tooltip follows the mouse.

How can this full page div be achieved? My many attempts have failed to create a div with any height.

I am away from my pc but can add what I’ve tried already soon.