JavaScript arrays are versatile and offer a wide range of built-in methods to manipulate, iterate, and manage data efficiently. Understanding these methods is crucial for effective programming. Let's delve into some commonly used array methods with practical examples.
let fruits = ['apple', 'banana']; fruits.push('orange'); // returns 3 (new length of array) console.log(fruits); // Output: ['apple', 'banana', 'orange']
let fruits = ['apple', 'banana', 'orange']; let lastFruit = fruits.pop(); // returns 'orange' console.log(fruits); // Output: ['apple', 'banana'] console.log(lastFruit); // Output: 'orange'
let fruits = ['apple', 'banana', 'orange']; let firstFruit = fruits.shift(); // returns 'apple' console.log(fruits); // Output: ['banana', 'orange'] console.log(firstFruit); // Output: 'apple'
let fruits = ['banana', 'orange']; fruits.unshift('apple'); // returns 3 (new length of array) console.log(fruits); // Output: ['apple', 'banana', 'orange']
let numbers = [1, 2, 3]; numbers.forEach(function(num) { console.log(num * 2); // Output: 2, 4, 6 });
let numbers = [1, 2, 3]; let doubled = numbers.map(function(num) { return num * 2; }); console.log(doubled); // Output: [2, 4, 6]
let numbers = [1, 2, 3, 4, 5]; let evens = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evens); // Output: [2, 4]
let numbers = [10, 20, 30, 40, 50]; let found = numbers.find(function(num) { return num > 25; }); console.log(found); // Output: 30
let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce(function(acc, current) { return acc current; }, 0); console.log(sum); // Output: 15 (1 2 3 4 5)
let fruits = ['apple', 'banana', 'orange', 'apple']; let index = fruits.indexOf('apple'); // returns 0 console.log(index); // Output: 0
let fruits = ['apple', 'banana', 'orange', 'apple']; let lastIndex = fruits.lastIndexOf('apple'); // returns 3 console.log(lastIndex); // Output: 3
These array methods are fundamental tools for manipulating data structures in JavaScript efficiently. By mastering these methods, you'll gain a powerful toolkit for handling arrays in various programming scenarios.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3