JavaScript array conversions and transformations
Aug 28, 2023 pm 11:41 PMArray is a basic and powerful data structure in programming. Their power comes not just from the ability to store multiple objects or values. They also expose a variety of tools that make it easy to manipulate and use the data they contain.
We often need to change arrays to meet specific needs. For example, you may need to reorganize the objects in an array so that it is ordered by the value of a specific property, or you may need to merge multiple arrays into a single array. In many cases, you may need to completely convert an array of objects into another array of completely different objects.
In this tutorial, you will learn about the tools provided by JavaScript for merging, copying, transforming, and filtering arrays. However, before I begin, I must point out that although I use the terms "merge", "convert", "convert" and "filter", these processes rarely change existing arrays. Instead, they create a new array containing the merged, transformed, transformed, and filtered data, leaving the original array unchanged in its original format.
Jump to the content of this section:
- Merge array
- Copy Array
- Convert array to string
- Convert array
- Filter array
Merge array
Maybe you are processing data from different sources, or maybe you have multiple arrays and want to combine them into a single array to make it easier to process them. Whatever the reason, sometimes you need to combine multiple arrays into a single array. JavaScript provides us with two ways to combine arrays. You can use the concat()
method or the spread operator (...
).
concat()
The method is used to merge two or more arrays and return a new array containing the elements of the merged arrays. The new array will first be filled with elements from the array object on which you called the method. It will then be filled with the elements of the array object you passed to the method. For example:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const mergedArray = array1.concat(array2); console.log(mergedArray); // output: [1, 2, 3, 4, 5, 6]
In this code, we have two arrays, array1
and array2
. We merge these arrays into a new array called mergedArray
using the concat()
method, you can see that the resulting array contains the elements [1, 2, 3 , 4, 5, 6]
. The following example changes the code to call the concat()
method on array2
:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const mergedArray2 = array2.concat(array1); console.log(mergedArray2); // output: [4, 5, 6, 1, 2, 3]
Note that in this code, the order of the elements in the resulting array is different: [4, 5, 6, 1, 2, 3]
. So if element order is important to you, be sure to use concat()
in the order you want.
The spread operator, on the other hand, allows you to extend the elements of an array, and you can use it in a new array literal to merge arrays. For example:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const mergedArray = [...array1, ...array2]; console.log(mergedArray); // output: [1, 2, 3, 4, 5, 6]
Here we again have two arrays, array1
and array2
, but we use the spread operator to merge them into one called mergedArray
in the new array. The end result is the same as the first concat()
example, but using this approach gives you (and those reading the code) a clearer understanding of how the mergedArray
is constructed and populated of.
Copy Array
There are several reasons why you might want to copy an array. You may want to preserve the original data of the array (if they are simple values), or you may want to avoid any unintended side effects from using or manipulating the array object itself. For whatever reason, JavaScript makes it very easy to create copies of arrays.
To create a copy of an array, you can use the slice()
method. This method returns a shallow copy of the array you called it on (more on this later). For example:
const originalArray = [1, 2, 3, 4, 5]; const copiedArray = originalArray.slice(); console.log(copiedArray); // output: [1, 2, 3, 4, 5]
This code defines an array named originalArray, we use the
slice()
method to create it copy without passing any parameters. copiedArray
The object contains the same values ??as the original, but it is a completely different array object.
You can also use the slice()
method to extract a portion of an array by specifying the start and end index.
const originalArray = [1, 2, 3, 4, 5]; const slicedArray = originalArray.slice(1, 4); console.log(slicedArray); // output: [2, 3, 4]
In this example, we create a slice array containing elements from index 1 to index 3 of the original array (excluding the ending index passed to the slice()
method).
什么是淺拷貝?
淺拷貝是指創(chuàng)建一個(gè)新的對(duì)象或數(shù)組,它是原始對(duì)象或集合的副本,但僅限于第一級(jí)。換句話說,淺拷貝復(fù)制原始對(duì)象的結(jié)構(gòu),但不復(fù)制其中包含的對(duì)象或元素。
當(dāng)您創(chuàng)建數(shù)組的淺表副本時(shí),新數(shù)組將擁有自己的一組引用,對(duì)與原始數(shù)組相同的對(duì)象或元素進(jìn)行引用。這意味著如果原始數(shù)組包含簡(jiǎn)單值(例如數(shù)字、字符串或布爾值),則淺拷貝將有效地創(chuàng)建具有相同值的新數(shù)組。但是,如果原始數(shù)組包含對(duì)象或其他引用類型(例如其他數(shù)組或?qū)ο螅?,則淺復(fù)制將僅復(fù)制對(duì)這些對(duì)象的引用,而不是對(duì)象本身。因此,對(duì)原始數(shù)組中的對(duì)象所做的任何更改也將反映在淺拷貝中,反之亦然,因?yàn)樗鼈內(nèi)匀灰脙?nèi)存中的相同對(duì)象。
相比之下,深層復(fù)制創(chuàng)建一個(gè)新的對(duì)象或集合,它是原始對(duì)象或集合的完整、獨(dú)立的副本,包括所有嵌套的對(duì)象或元素。這意味著對(duì)原始數(shù)組中的對(duì)象所做的更改不會(huì)影響深層復(fù)制,反之亦然,因?yàn)樗鼈冊(cè)趦?nèi)存中擁有自己的對(duì)象集。
下面是一個(gè)例子來說明差異:
const originalArray = [1, 2, { a: 3 }]; const shallowCopy = originalArray.slice(); const deepCopy = JSON.parse(JSON.stringify(originalArray)); originalArray[2].a = 4; console.log(shallowCopy); // output: [1, 2, { a: 4 }] console.log(deepCopy); // output: [1, 2, { a: 3 }]
在此示例中,shallowCopy
反映對(duì)原始數(shù)組所做的更改,而deepCopy
不受影響。< /p>
將數(shù)組轉(zhuǎn)換為字符串
數(shù)組是一種編程構(gòu)造,很多時(shí)候我們需要將數(shù)組轉(zhuǎn)換為字符串。也許我們需要向用戶呈現(xiàn)數(shù)組的內(nèi)容。也許我們需要將數(shù)組的內(nèi)容序列化為 JSON 以外的格式。
通過使用 join()
方法,您可以將數(shù)組轉(zhuǎn)換為字符串。默認(rèn)情況下,元素以逗號(hào)分隔,但您可以通過將字符串作為參數(shù)傳遞給 join()
方法來指定自定義分隔符。例如:
const fruitArray = ['apple', 'banana', 'cherry']; const fruitString = fruitArray.join(', '); console.log(fruitString); // output: &quot;apple, banana, cherry&quot;
在此示例中,我們有一個(gè)名為 fruitArray
的數(shù)組,我們使用 join()
方法將其轉(zhuǎn)換為字符串自定義分隔符 - 逗號(hào)后跟空格。
使用 join()
的一個(gè)更有用的示例是從包含 URL 查詢字符串參數(shù)的數(shù)組中輸出 URL 查詢字符串,如下所示:
const queryParamsArray = [ 'search=JavaScript', 'page=1', 'sort=relevance', ]; const queryString = queryParamsArray.join('&amp;'); const url = 'https://example.com/api?' + queryString; console.log(url); // output: &quot;https://example.com/api?search=JavaScript&amp;page=1&amp;sort=relevance&quot;
在此代碼中,我們有一個(gè)名為 queryParamsArray
的數(shù)組,其中包含一組查詢字符串參數(shù)。然后,我們使用 join()
方法將數(shù)組的元素與 &
分隔符連接起來,形成一個(gè)查詢字符串。最后,我們通過將查詢字符串附加到基本 URL 來構(gòu)建完整的 URL。
生成 URL 查詢參數(shù)字符串是使用 join()
的常見用例。但是,您將使用一組復(fù)雜的對(duì)象,而不是像本示例中所示的簡(jiǎn)單的預(yù)定義字符串,然后必須將其轉(zhuǎn)換為可以連接在一起的字符串?dāng)?shù)組。
轉(zhuǎn)換數(shù)組
轉(zhuǎn)換數(shù)組的能力是 JavaScript 中最有用、最強(qiáng)大的功能之一。正如我在本教程前面提到的,您并不是真正轉(zhuǎn)換數(shù)組,而是創(chuàng)建一個(gè)包含轉(zhuǎn)換后的對(duì)象或值的新數(shù)組。原始數(shù)組未修改。
要轉(zhuǎn)換數(shù)組,請(qǐng)使用 map()
方法。它接受回調(diào)函數(shù)作為參數(shù),并為數(shù)組中的每個(gè)元素執(zhí)行該函數(shù)。
map(function (currentElement[, index, array]));
回調(diào)函數(shù)可以接受以下三個(gè)參數(shù):
-
currentElement
:當(dāng)前要轉(zhuǎn)換的元素(必填) -
index
:當(dāng)前元素的索引(可選) -
array
:調(diào)用map()
方法的數(shù)組(可選)
然后,回調(diào)函數(shù)的返回值將作為元素存儲(chǔ)在新數(shù)組中。例如:
const numbers = [1, 2, 3, 4, 5]; function square(number) { return number * number; } const squaredNumbers = numbers.map(square); console.log(squaredNumbers); // output: [1, 4, 9, 16, 25]
在此代碼中,我們有一個(gè)名為 numbers
的數(shù)組,并聲明一個(gè)名為 square
的函數(shù),該函數(shù)將數(shù)字作為輸入并返回該數(shù)字的平方。我們將 square
函數(shù)傳遞給 numbers.map()
以創(chuàng)建一個(gè)名為 squaredNumbers
的新數(shù)組,其中包含原始數(shù)字的平方值。 p>
但是讓我們看一個(gè)從對(duì)象數(shù)組構(gòu)建 URL 查詢字符串的示例。原始數(shù)組將包含具有 param
(對(duì)于參數(shù)名稱)和 value
(對(duì)于參數(shù)值)屬性的對(duì)象。
const queryParams = [ { param: 'search', value: 'JavaScript' }, { param: 'page', value: 1 }, { param: 'sort', value: 'relevance' }, ]; function createParams(obj) { return obj.param + '=' + obj.value; } const queryStringArray = queryParams.map(createParams); const queryString = queryStringArray.join('&amp;'); const url = 'https://example.com/api?' + queryString; console.log(url); // output: &quot;https://example.com/api?search=JavaScript&amp;page=1&amp;sort=relevance&quot;
在此示例中,我們有一個(gè)名為 queryParams
的數(shù)組,其中包含我們要轉(zhuǎn)換為查詢字符串的對(duì)象。我們聲明一個(gè)名為 createParams
的函數(shù),它接受一個(gè)對(duì)象作為輸入并返回格式為“param=value
”的字符串。然后,我們使用 map()
方法將 createParams
?函數(shù)應(yīng)用于原始數(shù)組中的每個(gè)對(duì)象,從而創(chuàng)建一個(gè)名為 queryStringArray
的新數(shù)組。
接下來,我們 join()
queryStringArray
創(chuàng)建最終的查詢字符串,使用 &
分隔符分隔每個(gè) param=value 對(duì),然后我們通過將查詢字符串附加到來構(gòu)造完整的 URL基本 URL。
使用 map()
方法是處理數(shù)組的重要部分,但有時(shí)我們只需要處理數(shù)組中的幾個(gè)元素。
過濾數(shù)組
filter()
方法允許您創(chuàng)建一個(gè)僅包含滿足給定條件的元素的新數(shù)組。這是通過將回調(diào)函數(shù)傳遞給 filter()
方法來實(shí)現(xiàn)的,該方法測(cè)試原始數(shù)組中的每個(gè)元素。如果回調(diào)函數(shù)返回true
,則該元素包含在新數(shù)組中;如果返回 false
,則排除該元素。
回調(diào)函數(shù)使用與 map()
方法的回調(diào)函數(shù)相同的簽名:
filter(function(currentElement[, index, array]));
currentElement
參數(shù)是必需的,但 index
和 array
是可選的。例如:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function isEven(number) { return number % 2 === 0; } const evenNumbers = numbers.filter(isEven); console.log(evenNumbers); // output: [2, 4, 6, 8, 10]
在此示例中,我們有一個(gè)名為 numbers
的數(shù)組。我們聲明一個(gè)名為 isEven
的函數(shù),它接受一個(gè)數(shù)字作為輸入,如果數(shù)字是偶數(shù)(即能被 2 整除),則返回 true
,否則返回 false
。我們通過使用 isEven
函數(shù)作為 filter()
方法的回調(diào)函數(shù)來過濾原始數(shù)組,從而創(chuàng)建一個(gè)名為 evenNumbers
的新數(shù)組。生成的 evenNumbers
數(shù)組僅包含原始數(shù)組中的偶數(shù)。
filter()
方法是處理數(shù)組的強(qiáng)大工具,允許您輕松提取相關(guān)數(shù)據(jù)或根據(jù)特定條件創(chuàng)建數(shù)組的子集。
結(jié)論
數(shù)組是 JavaScript 中最通用、最有用的對(duì)象之一,因?yàn)槲覀冇泄ぞ呖梢暂p松地合并、復(fù)制、轉(zhuǎn)換、轉(zhuǎn)換和過濾它們。這些技術(shù)中的每一種都有特定的用途,您可以通過各種方式將它們組合起來,以在 JavaScript 應(yīng)用程序中有效地操作和處理數(shù)組。通過理解和應(yīng)用這些方法,您將能夠更好地應(yīng)對(duì)涉及數(shù)組的各種編程挑戰(zhàn)。
當(dāng)您繼續(xù)發(fā)展 JavaScript 技能時(shí),請(qǐng)記住練習(xí)使用這些數(shù)組方法并探索該語(yǔ)言中可用的其他內(nèi)置數(shù)組函數(shù)。這將幫助您更加精通 JavaScript,并使您能夠編寫更高效、干凈且可維護(hù)的代碼。快樂編碼!
The above is the detailed content of JavaScript array conversions and transformations. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.
