Explain map() method in javascript with example program and output
视频信息
答案文本
视频字幕
Welcome to JavaScript's map method! The map method is one of the most useful array methods in JavaScript. It creates a new array by calling a provided function on every element in the original array. The key point is that map does not modify the original array - it always returns a completely new array.
Now let's look at the syntax of the map method. The basic syntax is array dot map, followed by a callback function. The callback function receives three parameters: the current element being processed, the index of that element, and the original array itself. The index and array parameters are optional - you only need to include them if your function uses them.
Let's see our first practical example. We have an array of numbers from 1 to 5, and we want to double each number. We use the map method with a function that takes each number and returns it multiplied by 2. The original array remains unchanged, and we get a new array with all the doubled values. Notice we can also write this using arrow function syntax for a more concise approach.
Here's another common use case for the map method: extracting specific properties from an array of objects. We have an array of user objects, each containing an id and name. Using map, we can easily create a new array containing only the names. The callback function accesses the name property of each user object and returns it. This transforms our array of objects into a simple array of strings.
To summarize what we've learned about the JavaScript map method: It creates a new array without modifying the original, making it perfect for functional programming. The callback function is applied to each element, and it returns an array of the same length with transformed values. The map method is an essential tool for modern JavaScript development and data transformation.