Home  >  Article  >  CMS Tutorial  >  JavaScript array conversions and transformations

JavaScript array conversions and transformations

WBOY
WBOYOriginal
2023-08-28 23:41:101016browse

JavaScript 数组转换和转换

Array 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).

什么是浅拷贝?

浅拷贝是指创建一个新的对象或数组,它是原始对象或集合的副本,但仅限于第一级。换句话说,浅拷贝复制原始对象的结构,但不复制其中包含的对象或元素。

当您创建数组的浅表副本时,新数组将拥有自己的一组引用,对与原始数组相同的对象或元素进行引用。这意味着如果原始数组包含简单值(例如数字、字符串或布尔值),则浅拷贝将有效地创建具有相同值的新数组。但是,如果原始数组包含对象或其他引用类型(例如其他数组或对象),则浅复制将仅复制对这些对象的引用,而不是对象本身。因此,对原始数组中的对象所做的任何更改也将反映在浅拷贝中,反之亦然,因为它们仍然引用内存中的相同对象。

相比之下,深层复制创建一个新的对象或集合,它是原始对象或集合的完整、独立的副本,包括所有嵌套的对象或元素。这意味着对原始数组中的对象所做的更改不会影响深层复制,反之亦然,因为它们在内存中拥有自己的对象集。

下面是一个例子来说明差异:

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反映对原始数组所做的更改,而deepCopy不受影响。

将数组转换为字符串

数组是一种编程构造,很多时候我们需要将数组转换为字符串。也许我们需要向用户呈现数组的内容。也许我们需要将数组的内容序列化为 JSON 以外的格式。

通过使用 join() 方法,您可以将数组转换为字符串。默认情况下,元素以逗号分隔,但您可以通过将字符串作为参数传递给 join() 方法来指定自定义分隔符。例如:

const fruitArray = ['apple', 'banana', 'cherry'];
const fruitString = fruitArray.join(', ');

console.log(fruitString); // output: "apple, banana, cherry"

在此示例中,我们有一个名为 fruitArray 的数组,我们使用 join() 方法将其转换为字符串自定义分隔符 - 逗号后跟空格。

使用 join() 的一个更有用的示例是从包含 URL 查询字符串参数的数组中输出 URL 查询字符串,如下所示:

const queryParamsArray = [
  'search=JavaScript',
  'page=1',
  'sort=relevance',
];

const queryString = queryParamsArray.join('&');

const url = 'https://example.com/api?' + queryString;
console.log(url); // output: "https://example.com/api?search=JavaScript&page=1&sort=relevance"

在此代码中,我们有一个名为 queryParamsArray 的数组,其中包含一组查询字符串参数。然后,我们使用 join() 方法将数组的元素与 & 分隔符连接起来,形成一个查询字符串。最后,我们通过将查询字符串附加到基本 URL 来构建完整的 URL。

生成 URL 查询参数字符串是使用 join() 的常见用例。但是,您将使用一组复杂的对象,而不是像本示例中所示的简单的预定义字符串,然后必须将其转换为可以连接在一起的字符串数组。

转换数组

转换数组的能力是 JavaScript 中最有用、最强大的功能之一。正如我在本教程前面提到的,您并不是真正转换数组,而是创建一个包含转换后的对象或值的新数组。原始数组未修改。

要转换数组,请使用 map() 方法。它接受回调函数作为参数,并为数组中的每个元素执行该函数。

map(function (currentElement[, index, array]));

回调函数可以接受以下三个参数:

  • currentElement:当前要转换的元素(必填)
  • index:当前元素的索引(可选)
  • array:调用 map() 方法的数组(可选)

然后,回调函数的返回值将作为元素存储在新数组中。例如:

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]

在此代码中,我们有一个名为 numbers 的数组,并声明一个名为 square 的函数,该函数将数字作为输入并返回该数字的平方。我们将 square 函数传递给 numbers.map() 以创建一个名为 squaredNumbers 的新数组,其中包含原始数字的平方值。 p>

但是让我们看一个从对象数组构建 URL 查询字符串的示例。原始数组将包含具有 param (对于参数名称)和 value (对于参数值)属性的对象。

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('&');

const url = 'https://example.com/api?' + queryString;
console.log(url); // output: "https://example.com/api?search=JavaScript&page=1&sort=relevance"

在此示例中,我们有一个名为 queryParams 的数组,其中包含我们要转换为查询字符串的对象。我们声明一个名为 createParams 的函数,它接受一个对象作为输入并返回格式为“param=value”的字符串。然后,我们使用 map() 方法将 createParams 函数应用于原始数组中的每个对象,从而创建一个名为 queryStringArray 的新数组。

接下来,我们 join() queryStringArray 创建最终的查询字符串,使用 & 分隔符分隔每个 param=value 对,然后我们通过将查询字符串附加到来构造完整的 URL基本 URL。

使用 map() 方法是处理数组的重要部分,但有时我们只需要处理数组中的几个元素。

过滤数组

filter() 方法允许您创建一个仅包含满足给定条件的元素的新数组。这是通过将回调函数传递给 filter() 方法来实现的,该方法测试原始数组中的每个元素。如果回调函数返回true,则该元素包含在新数组中;如果返回 false,则排除该元素。

回调函数使用与 map() 方法的回调函数相同的签名:

filter(function(currentElement[, index, array]));

currentElement 参数是必需的,但 indexarray 是可选的。例如:

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]

在此示例中,我们有一个名为 numbers 的数组。我们声明一个名为 isEven 的函数,它接受一个数字作为输入,如果数字是偶数(即能被 2 整除),则返回 true ,否则返回 false 。我们通过使用 isEven 函数作为 filter() 方法的回调函数来过滤原始数组,从而创建一个名为 evenNumbers 的新数组。生成的 evenNumbers 数组仅包含原始数组中的偶数。

filter() 方法是处理数组的强大工具,允许您轻松提取相关数据或根据特定条件创建数组的子集。

结论

数组是 JavaScript 中最通用、最有用的对象之一,因为我们有工具可以轻松地合并、复制、转换、转换和过滤它们。这些技术中的每一种都有特定的用途,您可以通过各种方式将它们组合起来,以在 JavaScript 应用程序中有效地操作和处理数组。通过理解和应用这些方法,您将能够更好地应对涉及数组的各种编程挑战。

当您继续发展 JavaScript 技能时,请记住练习使用这些数组方法并探索该语言中可用的其他内置数组函数。这将帮助您更加精通 JavaScript,并使您能够编写更高效、干净且可维护的代码。快乐编码!

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!

Statement:
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