📜  touppercase javascript 数组 - Javascript (1)

📅  最后修改于: 2023-12-03 14:48:01.430000             🧑  作者: Mango

Converting an Array to Uppercase in JavaScript

Working with arrays in JavaScript is a common task for developers. When dealing with textual data, one common operation is converting all the elements in an array to uppercase. In JavaScript, you can achieve this easily with just a few lines of code.

The map() method

One way to convert all elements in an array to uppercase is by using the map() method. This method creates a new array with the results of calling a provided function on every element in the original array.

To use map() to convert all elements to uppercase, you can provide a function that returns the uppercase version of each element. Here's an example:

const array = ['apple', 'banana', 'pear'];
const uppercaseArray = array.map(element => element.toUpperCase());
console.log(uppercaseArray); // ['APPLE', 'BANANA', 'PEAR']

In this example, the map() method is used on the original array array. The function provided to map() takes each element in array and converts it to uppercase using the toUpperCase() method. The result is a new array with all elements in uppercase.

The forEach() method

Another way to convert all elements in an array to uppercase is by using the forEach() method. This method executes a provided function once for each array element.

To use forEach() to convert all elements to uppercase, you can provide a function that modifies each element in place. Here's an example:

const array = ['apple', 'banana', 'pear'];
array.forEach((element, index) => {
  array[index] = element.toUpperCase();
});
console.log(array); // ['APPLE', 'BANANA', 'PEAR']

In this example, the forEach() method is used on the original array array. The function provided to forEach() takes each element and converts it to uppercase using the toUpperCase() method. The modified element is then stored back into the original array using its index.

Conclusion

Converting all elements in an array to uppercase is a common task in JavaScript. There are multiple ways to achieve this, but using the map() method or the forEach() method are two of the most common approaches. With just a few lines of code, you can easily convert any array to uppercase in JavaScript.