Array Methods (map)
Stryg for at vise menuen
The map method is a powerful tool for transforming arrays in JavaScript. It allows you to create a new array by applying a function to each element of an existing array. The original array remains unchanged, making map a non-mutating method.
12345const numbers = [1, 2, 3, 4]; const doubled = numbers.map(function(number) { return number * 2; }); console.log(doubled); // Output: [2, 4, 6, 8]
When you call array.map(callback), the callback function is executed once for every element in the array. The callback receives up to three arguments:
- The current element value;
- The current element's index;
- The original array.
Most commonly, you will use only the first parameter—the current value. The function you provide should return a value, which will become the corresponding element in the new array.
This makes map ideal for tasks like:
- Converting numbers to strings;
- Modifying each object in an array of objects;
- Extracting a specific property from each object in an array.
Since map always returns a new array, you can chain it with other array methods or use it to keep your data transformations clear and predictable.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat