Javascript, clone array but when function called the original array is altered as well [duplicate]

I have created a very simple example to show the problem I am facing when using creating an array object in Javascript.

I want to clone the array and call a function, inside that function I want to be able to change a team name to another and return it, when I do this the original value is also changed.

I have made this super simplistic to illustrate the problem.

a = [];
a[0]    = {};
a[0].team = "Arsenal";
    
a[1]    = {};
a[1].team = "Chelsea";

a[2]    = {};
a[2].team = "West Ham";

function change_team(d, club){
    d[1].team = club;
    return d;
};

b = [...a]; // Clone a[];
change_team(b, "spurs");

// Should read Arsenal, Chelsea, West Ham;
for(n=0; n<a.length; n++){
    console.log(n+"] "+a[n].team);
};

// Should read Arsenal, Spurs, West Ham;
for(n=0; n<a.length; n++){
    console.log(n+"] "+b[n].team);
};

The “CefSharp” object in the JavaScript of my loaded html is “undefined”

I’m putting together a WinForm project that hosts CefSharp in one of the Forms. I’ve setup the browser and rendered it in my main form. The problem is that when I try to bind a C# object via the browser.JavascriptObjectRepository API, I keep getting Uncaught ReferenceError: CefSharp is not defined.

I’d like to know if I’m missing something in my setup process.

Below is the code.


    public partial class MainWindow : Form
    {
        private readonly ChromiumViewModel BrowserViewModel;
        private readonly ChromiumWebBrowser browser;
        private readonly IServiceProvider serviceProvider;

        public MainWindow(
            IServiceProvider serviceProvider)
        {
            InitializeComponent();

            this.serviceProvider = serviceProvider;
            browser = InitializeBrowser();
        }

        private ChromiumWebBrowser InitializeBrowser()
        {
            var cefSettings = new CefSettings();
            cefSettings.BrowserSubprocessPath = Environment.ProcessPath!;
            cefSettings.RegisterScheme(new CefCustomScheme
            {
                SchemeName = "http",
                DomainName = "abc.xyz",
                SchemeHandlerFactory = new FolderSchemeHandlerFactory(
                    rootFolder: Path.Combine(Environment.CurrentDirectory, "Html"),
                    hostName: "abc.xyz", //Optional param no hostname/domain checking if null
                    defaultPage: "index.html") //Optional param will default to index.html
            });

            Cef.Initialize(cefSettings);

            var browser = new ChromiumWebBrowser("http://abc.xyz")
            {
                Dock = DockStyle.Fill
            };
            Controls.Add(browser);

            browser.LoadingStateChanged += OnBrowserLoadingStateChanged;
            browser.ConsoleMessage += OnBrowserConsoleMessage;
            browser.StatusMessage += OnBrowserStatusMessage;
            browser.TitleChanged += OnBrowserTitleChanged;
            browser.AddressChanged += OnBrowserAddressChanged;

            var context = Context
                .NewBuilder()
                .Build();

            browser.JavascriptObjectRepository.ResolveObject += (sender, e) =>
            {
                var repo = e.ObjectRepository;
                if (e.ObjectName == "hostContext")
                {
                    var bindingOptions = BindingOptions.DefaultBinder;
                    repo.NameConverter = new CamelCaseJavascriptNameConverter();
                    repo.Register("hostContext", context, bindingOptions);
                }
            };

            return browser;
        }

        #region Browser Call-backs
        private void OnBrowserAddressChanged(object? sender, AddressChangedEventArgs e)
        {
        }

        private void OnBrowserTitleChanged(object? sender, TitleChangedEventArgs e)
        {
        }

        private void OnBrowserStatusMessage(object? sender, StatusMessageEventArgs e)
        {
        }

        private void OnBrowserConsoleMessage(object? sender, ConsoleMessageEventArgs e)
        {
        }

        private void OnBrowserLoadingStateChanged(object? sender, LoadingStateChangedEventArgs args)
        {
            //Wait for the Page to finish loading
            if (args.IsLoading == false)
            {
                browser.ExecuteScriptAsyncWhenPageLoaded("console.log(CefSharp)");
                //browser.ShowDevTools();
            }
        }
        #endregion

        protected override void OnClosed(EventArgs e)
        {
            serviceProvider.As<IDisposable>().Dispose();

            base.OnClosed(e);
        }
    }

PS: I discovered this issue while trying to call CefSharp.BindObjectAsync("hostContext") both in the *.javascript file, and using browser.ExecuteScriptAsyncWhenPageLoaded(...).

Nuget versions:
nuget-versions

Thanks!

Problem with Database in frame work adoins js

i have error in when i using Database.from , the error is the from is not function

my code :

import vine, { SimpleMessagesProvider } from '@vinejs/vine';
import {Database} from '@adonisjs/lucid/database'

userName: vine.string().unique(async (value, field) => {
        const exists = await Database.from('chef').where('chefUserName', value).first();
        return !exists; // Return true if the username is unique
      }).minLength(4).maxLength(10).regex(/^[a-zA-Z0-9_]+$/),

i try to check from package.json if any thing not exist but every thing is fine

Suitescript 2.x Custom module script is not working with Render module

I’m trying to call a script with a button that I created on specific file type. It originally called a client script but I realized the render module is for server scripts only. I thought switching to a custom module would allow me to use the render module but I keep getting the same error I got with the client script. Is there another script type I should be using or is there something wrong with my code?

Error that shows up in the console

Custom module script:

/**
*send_invoice_from_button_CM.js
*@NApiVersion 2.x
*@NModuleScope Public
*/

define(['N/record', 'N/render'], 

/**
 * 
 * @param {record} record 
 * @param {render} render 
 * @returns 
 */



    function (record, render) {

        function customButtonSendInvoice(transaction){
            console.log("The button is working.")
        }

        return{
            customButtonSendInvoice: customButtonSendInvoice
        }
    });

Check using Iframe/JS/? if user was on a website in last 30 days

Situation:

  • I’m the owner of the website example.com
  • I want to give my customers the possibility (pixel/iframe/sth?) to check if current visitor of their website was on my website (example.com) in the last 30 days
  • If she/he was on my website in the last 30 days, the dataLayer event should be fired.

Tried Iframe and embeded JS to read cookies but no success.

Why does console.log report the value of my variable, but return doesn’t?

I’m working through a coding interview practice question. The prompt:

A company assigns each customer a membership ID, and you are
implementing a check digit for those IDs.

The check digit should be calculated by adding up all digits in each
membership ID. If the result of the sum is a number with more than a
single digit, another iteration is required, and the digits of the
result also should be added together. This process should repeat until
a single-digit number is calculated.

Example: for membership ID ‘55555’, the sum of all digits is 25.
Because this is not a single-digit number, 2 and 5 would be added, and
the result would be 7, which is the check digit.

So I’m attempting a recursive strategy for this. I seem to have been able to get the correct answer for a variety of queries, but I can’t understand why my return in my base case is returning undefined, but the console.log just above it returns the correct value of 7. Thoughts?

function createCheckDigit(membershipId) {
  // Write the code that goes here.
  let checkDigit = membershipId;
  if ([...checkDigit].length === 1) {
    console.log(checkDigit); // this prints 7
    return checkDigit; // why doesn't this return 7?
  } else {
    let mIdList = [...checkDigit];
    sum = 0;
    for (let c in mIdList) {
      sum += Number(mIdList[c]);
    }
    createCheckDigit(sum.toString());
  };
}

console.log(createCheckDigit("55555"));

How do increment and decrement work with recursion

I can’t understand how increment works with recursion.So if i have returned value which require calling the function before adding specific value.

let x = 0;

function func(n) {
  if (n > 0) {
    x++;
    return func(n - 1) + x;
  }
  return 0;
}

console.log(func(5));

why the output is not 15.

func(5) = func(4) + 1
func(4) = func(3) + 2
func(4) = func(2) + 3
func(2) = func(1) + 4
func(1) = func(0) + 5
func(0) = 0

then after unwind it the result is 15 not 25 as it has compiled.

How do I use jQuery promises to chain one ajax call, then a loop of ajax calls, then make use of an accumulated result?

I am struggling mightily to figure out the correct use of $.when, .then or .done, and probably $.each to achieve what I need here. Everything I try fails in one way or another: code runs out of order, a call doesn’t get made at all, etc.

I need to create a function that does the following things in this specific order:

  1. Makes an ajax call to retrieve the Name of a table based on its ID (which is the value from a dropdown on the page; the dropdown has already been retrieved with jQuery):
// querying UserEntities(id) returns certain metadata for the user-created table with that ID
$.ajax({
   type: 'GET',
   url: serviceURL + 'UserEntities(' + entity.val() + ')',
   dataType: 'json',
   processData: true,
   success: function (tblData) {
      return tblData.value[0].Name;
   }
})
  1. Using the retrieved table Name from step 1 (tblName in the code below), loops through an array of objects to see if a certain property of that object appears in a certain column of the table, building up an array of the objects that do appear:
$.each(items, function (i, item) {
   $.ajax({
      type: 'GET',
      url: serviceURL + tblName + '?$filter=' + attributeName + ' eq '' + item.MyPropName+ ''&$top=0&$count=true',
      dataType: 'json',
      processData: true,
      success: function (data) {
         if (data["@odata.count"] && data["@odata.count"] > 0) {
            itemsInTable.push(item);
         } else {
            // ...do some simple thing on the page...
         }
      }
   });
});
  1. Generates a popup with the list of items that appear in the table:
if (itemsInTable.length > 0) {
   // ...do some stuff...
}

To be clear, I am not asking how to make a popup. This is purely about making sure all the ajax calls get made – and in the proper order – before the code ever gets to part 3 where it’s checking the length of the array. Step 1 needs to finish before step 2, and then step 2 needs to finish (every ajax call in the loop has to complete) before step 3.

Onclick event not working in Blazor Web Assembly 8.0

I am studying a Blazor course and I noticed the button click event does not trigger on button click. I created a simple Blazor web assembly 8.0 project to confirm the issue. I noticed on button click nothing happened.

I added @rendermode InteractiveServer to my test page and also these methods to my program.cs, but nothing happened.

builder.Services.AddRazorComponents().AddInteractiveServerComponents()

app.MapRazorComponents<App>().AddInteractiveServerRenderMode();

Program.cs

using BlazorApp1.Components;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents();
builder.Services.AddRazorComponents().AddInteractiveServerComponents();

var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
  app.UseExceptionHandler("/Error", createScopeForErrors: true);
  app.UseHsts();
}

app.MapRazorComponents<App>().AddInteractiveServerRenderMode();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents<App>();
app.Run();

Test.razor

@page "/test"
@rendermode InteractiveServer
@inject IJSRuntime JsRuntime
<h3>Test JavaScript Interop</h3>
<button type="button" @onclick="TestJsInterop">Click Me</button>

@code {
  private async Task TestJsInterop()
  {
    // Call the custom JS function showCustomAlert
    await JsRuntime.InvokeVoidAsync("showCustomAlert", "Hello from custom JS interop!");
  }
}
window.showCustomAlert = function (message) {
  alert(message); // This is the native JS alert function
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BlazorApp</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
</head>
<body>
    <app>
        <!-- The component rendered in InteractiveServer mode will be mounted here -->
    </app>
    <script src="_framework/blazor.server.js"></script>
<script src="js/spp.js"></script>

</body>
</html>

The weird part is that the counter button works perfectly well in the counter page.

I also Updated Routes element in App.razor file with <Routes @rendermode=RenderMode.InteractiveServer /> and <script src="_framework/blazor.web.js"></script>

I want the button click event to display an alert with message “Hello from custom JS interop!”

Please help me fix this error as I can’t forge ahead with my Blazor tutorial.

Submitting data once a file is uploaded not when submit is clicked

I have a form and am trying to call my api when a file is uploaded. Currently it only works when the user clicks a submit button. How can I get it to call my api with handleFileChange? The fetch request only works in for the handleSubmit function. Here is my html:

  <form className={styles['resume-form']} onSubmit={handleSubmit}>
          <div className="relative">
            <input
              type="file"
              accept=".pdf, .doc, .docx"
              id="fileInput"
              className="hidden"
              onChange={handleFileChange}
            />
            <label
              htmlFor="fileInput"
              className="bg-yellow-500 text-white py-2 px-4 rounded cursor-pointer hover:bg-yellow-600"
            >
              Choose a file
            </label>
          </div>        
        <button type="submit" id="reviewer" className={styles['submit-button']}>Submit</button>
      </form>

Here is my javascript code:

const handleFileChange = async (e) => {
    setResumeFile(e.target.files[0]);
    console.log("test")

    try {
      const formData = new FormData();
      console.log("test1")
      formData.append('resume', resumeFile);
      const response = await fetch('/api/analyze_resume', {
              method: 'POST',
              body: formData,
              headers: {
                // Note: No need to set 'Content-Type' for FormData as it is automatically set
              },
      });

      const responseData = await response.json();
      setReviewResult(responseData);
    } catch (error) {
      console.error('Error submitting resume:', error);
    }
  };

  const handleFileUpload = async (file) => {
    setResumeFile(file);
     e.preventDefault();

    try {
      const formData = new FormData();
      formData.append('resume', resumeFile);
      const response = await fetch('/api/analyze_resume', {
              method: 'POST',
              body: formData,
              headers: {
                // Note: No need to set 'Content-Type' for FormData as it is automatically set
              },
            });

      const responseData = await response.json();
      setReviewResult(responseData);
    } catch (error) {
      console.error('Error submitting resume:', error);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const formData = new FormData();
      formData.append('resume', resumeFile);
      const response = await fetch('/api/analyze_resume', {
              method: 'POST',
              body: formData,
              headers: {
                // Note: No need to set 'Content-Type' for FormData as it is automatically set
              },
            });

      const responseData = await response.json();
      setReviewResult(responseData);
    } catch (error) {
      console.error('Error submitting resume:', error);
    }
  };

How to stop event preventDefault()?

i tried to stop event.preventDefault() white using it in a function and used removeEventListener() and it didn’t work, and i used stopPropagation() and stopImmediatePropagation() and these didn’t work too.
so how can i stop event.preventDefault()?

how to get different filenames in chunk files after build in nextjs14 to avoid cache?

After each build I want the chunk files generated has different names.

Example:

<link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/webpack-653a0787c4442713.js"/>
<script src="/_next/static/chunks/fd9d1056-1a173cac11a1f73c.js" async=""></script>
<script src="/_next/static/chunks/23-5b35c9eea0c04c88.js" async=""></script>
<script src="/_next/static/chunks/main-app-f12028dd9bfdf9fd.js" async=""></script>
<script src="/_next/static/chunks/223-58572653937c7966.js" async=""></script>

“main-app-{…..}.js” is cached in my server side and after each build I’ve problems with user render side.

How to prevent the arrow keys from showing a ring around this input?

If I click the div that has tabIndex={0}, then press the arrow keys, a ring will appear around it. But I only want the ring to appear when I’m selecting it with Tab.

// TS:

const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
  event.preventDefault();
    
  // more code
}

// TSX:

<div
  tabIndex={0}
  className="relative w-full rounded outline-none ring-foreground ring-offset-2 focus-visible:ring-2"
  onKeyDown={handleKeyDown}
>
  <div
    className={cn(
      'flex h-10 w-full cursor-pointer items-center justify-between rounded border border-border bg-background px-3 py-2 text-sm shadow hover:shadow-dark'
    )}
  />
</div>

How to solve this issue? Note: event.preventDefault(); didn’t solve the issue.