Home Web Front-end Front-end Q&A How to implement addition, deletion, modification and query in javascript (code example)

How to implement addition, deletion, modification and query in javascript (code example)

Apr 25, 2023 pm 04:28 PM

As a powerful programming language, JavaScript can not only be used for interactive development of web pages, but also for processing data, operating DOM elements, etc. Among them, addition, deletion, modification and query are functions we often use. Let us take a look at the JavaScript code to implement addition, deletion, modification and query.

1. Add

The most common scenario for adding data is form submission. For example, we need to add the form data filled in by the user to an array. The following is a simple form submission code:

var form = document.querySelector('form');
var inputs = form.querySelectorAll('input');
var data = [];

form.addEventListener('submit', function(event) {
  event.preventDefault();
  var item = {};
  inputs.forEach(function(input) {
    item[input.name] = input.value;
  });
  data.push(item);
});

We first obtain the form and all input box elements in it, and then listen to the submit event of the form. In the event handling function, we create an empty object, use forEach to traverse all input box elements, use their name attribute as the attribute name of the object, use their value attribute as the attribute value, and finally add the object to the data array. . Note that we need to call the preventDefault() method to prevent the form from automatically submitting.

2. Delete

Deleting data is also a very common scenario. Usually we will delete one or more data items based on a certain condition. The following is a simple deletion code:

var id = 1; // 删除的数据ID
var index = data.findIndex(function(item) {
  return item.id === id;
});

if (index !== -1) {
  data.splice(index, 1);
}

We first define the data ID to be deleted, and then use the findIndex method to find the subscript of the first data item whose ID is equal to the ID (if not found, it returns -1 ). If found, the splice method is called to delete the data item.

3. Modify

Modifying data requires us to first find the data item to be modified, and then update its attribute value. The following is a simple modification code:

var id = 1; // 修改的数据ID
var index = data.findIndex(function(item) {
  return item.id === id;
});

if (index !== -1) {
  data[index].name = '新的名称';
}

We also first find the data item subscript corresponding to the data ID to be modified, and then determine whether the data item exists. If it exists, update its name attribute value to the new name.

4. Query

There are many ways to query data. The most common is to filter data according to a certain condition. The following is a simple query code:

var query = '张三'; // 查询的条件
var results = data.filter(function(item) {
  return item.name.includes(query);
});

console.log(results);

We define The conditions to be queried, and then use the filter method to filter all data items that meet the conditions and create a new array. In the example, we choose to query based on the name attribute containing query conditions, and finally output the results to the console.

The above is the code for adding, deleting, modifying and checking in JavaScript. They are functions we often use in daily development and play an important role in the background development and data management of applications. Hope this article can be helpful to you.

The above is the detailed content of How to implement addition, deletion, modification and query in javascript (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1511
276
A Deep Dive into WebAssembly (WASM) for Front-End Developers A Deep Dive into WebAssembly (WASM) for Front-End Developers Jul 27, 2025 am 12:32 AM

WebAssembly(WASM)isagame-changerforfront-enddevelopersseekinghigh-performancewebapplications.1.WASMisabinaryinstructionformatthatrunsatnear-nativespeed,enablinglanguageslikeRust,C ,andGotoexecuteinthebrowser.2.ItcomplementsJavaScriptratherthanreplac

Server-Side Rendering with Next.js Explained Server-Side Rendering with Next.js Explained Jul 23, 2025 am 01:39 AM

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS

Security Headers for Frontend Applications Security Headers for Frontend Applications Jul 18, 2025 am 03:30 AM

Front-end applications should set security headers to improve security, including: 1. Configure basic security headers such as CSP to prevent XSS, X-Content-Type-Options to prevent MIME guessing, X-Frame-Options to prevent click hijacking, X-XSS-Protection to disable old filters, HSTS to force HTTPS; 2. CSP settings should avoid using unsafe-inline and unsafe-eval, use nonce or hash and enable reporting mode testing; 3. HTTPS-related headers include HSTS automatic upgrade request and Referrer-Policy to control Referer; 4. Other recommended headers such as Permis

Frontend Development for Virtual Reality (VR) on Web Frontend Development for Virtual Reality (VR) on Web Jul 19, 2025 am 02:35 AM

The core of VR web front-end development lies in performance optimization and interactive design. You need to use WebXR to build a basic experience and check device support; choose A-Frame or Three.js framework development; uniformly process input logic of different devices; improve performance by reducing drawing calls, controlling model complexity, and avoiding frequent garbage collection; design UI and interactions that adapt to VR characteristics, such as gaze clicks, controller status recognition and reasonable layout of UI elements.

Frontend Error Monitoring and Logging Solutions Frontend Error Monitoring and Logging Solutions Jul 20, 2025 am 01:39 AM

The core of front-end error monitoring and logging is to discover and locate problems as soon as possible, and avoid user complaints before knowing them. 1. Basic error capture requires the use of window.onerror and window.onunhandledrejection to catch JS exceptions and Promise errors; 2. When selecting the error reporting system, give priority to tools such as Sentry, LogRocket, Bugsnag, and pay attention to SourceMap support, user behavior tracking and grouping statistics functions; 3. The reported content should include browser information, page URL, error stack, user identity and network request failure information; 4. Control the log frequency to avoid log explosion through strategies such as deduplication, current limiting, and hierarchical reporting.

Understanding the JavaScript Event Delegation Pattern Understanding the JavaScript Event Delegation Pattern Jul 21, 2025 am 03:46 AM

Event delegation is a technique that uses the event bubble mechanism to hand over the event processing of child elements to the parent element. It reduces memory consumption and supports dynamic content management by binding listeners on parent elements. The specific steps are: 1. Binding event listeners to the parent container; 2. Use event.target to determine the child elements that trigger the event in the callback function; 3. Execute the corresponding logic based on the child elements. Its advantages include improving performance, simplifying code maintenance and adapting to dynamically added elements. When using it, you should pay attention to event bubble restrictions, avoid excessive centralized monitoring, and reasonably select parent elements.

Optimizing Font Loading for Web Performance Optimizing Font Loading for Web Performance Jul 18, 2025 am 03:55 AM

Web page loading speed can be improved by optimizing font loading. 1. Use font-display:swap, allowing the system font to be displayed first and then replaced with custom fonts to avoid blank text; 2. Preload the first-screen keyword font to shorten the loading delay; 3. Reduce the number of font variants and formats, only load the necessary font weights and give priority to the use of woff2 format; 4. In response to the problem of excessive Chinese fonts, you can load the character set as needed or use system font alternatives to improve the first drawing time and reading experience.

Performance-First State Management with Zustand Performance-First State Management with Zustand Jul 25, 2025 am 04:32 AM

Zustandisalightweight,performantstatemanagementsolutionforReactappsthatavoidsRedux’sboilerplate;1.Useselectivestateslicingtopreventunnecessaryre-rendersbyselectingonlytheneededstateproperty;2.ApplycreateWithEqualityFnwithshalloworcustomequalitychecks

See all articles