Rumah >hujung hadapan web >tutorial js >Operator Spread dan Rest dalam Javascript dengan EXAMPLE
Selebihnya dan operator spread ialah ciri berkuasa dalam JavaScript, membolehkan anda bekerja dengan tatasusunan, objek dan hujah fungsi dengan lebih berkesan. Kedua-duanya menggunakan sintaks yang sama (...) tetapi mempunyai tujuan yang berbeza.
Operator selebihnya digunakan untuk mengumpulkan semua elemen yang tinggal ke dalam tatasusunan. Ia biasanya digunakan dalam parameter fungsi untuk mengendalikan bilangan argumen yang berubah-ubah.
function sum(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); } console.log(sum(1, 2, 3, 4)); // Output: 10
Di sini, ...nombor mengumpulkan semua argumen yang dihantar ke fungsi jumlah ke dalam tatasusunan yang dipanggil nombor, yang kemudiannya boleh diproses.
Pengendali hamparan digunakan untuk mengembangkan elemen tatasusunan atau objek kepada elemen atau sifat individu.
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combinedArray = [...arr1, ...arr2]; console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
Dalam contoh ini, ...arr1 dan ...arr2 mengembangkan elemen arr1 dan arr2 ke dalam gabungan Array baharu.
Pengendali ini sangat berguna untuk mengendalikan tatasusunan, objek dan hujah fungsi dengan cara yang bersih dan ringkas.
.
.
.
.
.
Lebih lanjut mengenai Operator Spread dan Rest
.
.
.
.
.
Sudah tentu! Mari kita menyelami lebih dalam ke bahagian lain dan menyebarkan pengendali, meneroka konsep mereka dan pelbagai kes penggunaan dengan penjelasan dan contoh yang lebih terperinci.
operator rehat membolehkan anda mengumpul berbilang elemen dan menggabungkannya ke dalam tatasusunan. Ia biasanya digunakan dalam fungsi untuk mengendalikan bilangan argumen yang berubah-ubah atau untuk mengumpulkan "selebihnya" elemen apabila memusnahkan tatasusunan atau objek.
function multiply(factor, ...numbers) { return numbers.map(number => number * factor); } console.log(multiply(2, 1, 2, 3, 4)); // Output: [2, 4, 6, 8]
Penjelasan:
const [first, second, ...rest] = [10, 20, 30, 40, 50]; console.log(first); // Output: 10 console.log(second); // Output: 20 console.log(rest); // Output: [30, 40, 50]
Penjelasan:
const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4}; console.log(a); // Output: 1 console.log(b); // Output: 2 console.log(rest); // Output: {c: 3, d: 4}
Penjelasan:
pengendali penyebaran digunakan untuk mengembangkan elemen tatasusunan, objek atau boleh lelar ke dalam elemen atau sifat individu. Ia adalah bertentangan dengan pengendali selebihnya dan sangat berguna untuk menggabungkan, menyalin dan menghantar elemen.
const arr1 = [1, 2]; const arr2 = [3, 4]; const arr3 = [5, 6]; const combined = [...arr1, ...arr2, ...arr3]; console.log(combined); // Output: [1, 2, 3, 4, 5, 6]
Penjelasan:
const original = [1, 2, 3]; const copy = [...original]; console.log(copy); // Output: [1, 2, 3] console.log(copy === original); // Output: false (different references)
Penjelasan:
const obj1 = {x: 1, y: 2}; const obj2 = {y: 3, z: 4}; const merged = {...obj1, ...obj2}; console.log(merged); // Output: {x: 1, y: 3, z: 4}
Penjelasan:
function add(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; console.log(add(...numbers)); // Output: 6
Penjelasan:
Operator Rehat (...):
Spread Operator (...):
Both operators enhance code readability and maintainability by reducing boilerplate code and providing more flexible ways to handle data structures.
.
.
.
.
.
.
Real world Example
.
.
.
.
Let's consider a real-world scenario where the rest and spread operators are particularly useful. Imagine you are building an e-commerce platform, and you need to manage a shopping cart and process user orders. Here's how you might use the rest and spread operators in this context:
Suppose you have a function to add items to a user's shopping cart. The function should accept a required item and then any number of optional additional items. You can use the rest operator to handle this:
function addToCart(mainItem, ...additionalItems) { const cart = [mainItem, ...additionalItems]; console.log(`Items in your cart: ${cart.join(', ')}`); return cart; } // User adds a laptop to the cart, followed by a mouse and keyboard const userCart = addToCart('Laptop', 'Mouse', 'Keyboard'); // Output: Items in your cart: Laptop, Mouse, Keyboard
Explanation:
Now, let's say you want to process an order and send the user's cart items along with their shipping details to a function that finalizes the order. The spread operator can be used to merge the cart items with the shipping details into a single order object.
const shippingDetails = { name: 'John Doe', address: '1234 Elm Street', city: 'Metropolis', postalCode: '12345' }; function finalizeOrder(cart, shipping) { const order = { items: [...cart], ...shipping, orderDate: new Date().toISOString() }; console.log('Order details:', order); return order; } // Finalizing the order with the user's cart and shipping details const userOrder = finalizeOrder(userCart, shippingDetails); // Output: // Order details: { // items: ['Laptop', 'Mouse', 'Keyboard'], // name: 'John Doe', // address: '1234 Elm Street', // city: 'Metropolis', // postalCode: '12345', // orderDate: '2024-09-01T12:00:00.000Z' // }
Explanation:
Let's say you want to add a feature where the user can add multiple items to the cart, and the first item is considered a "featured" item with a discount. The rest operator can handle the additional items, and the spread operator can be used to create a new cart with the updated featured item:
function addItemsWithDiscount(featuredItem, ...otherItems) { const discountedItem = { ...featuredItem, price: featuredItem.price * 0.9 }; // 10% discount return [discountedItem, ...otherItems]; } const laptop = { name: 'Laptop', price: 1000 }; const mouse = { name: 'Mouse', price: 50 }; const keyboard = { name: 'Keyboard', price: 70 }; const updatedCart = addItemsWithDiscount(laptop, mouse, keyboard); console.log(updatedCart); // Output: // [ // { name: 'Laptop', price: 900 }, // { name: 'Mouse', price: 50 }, // { name: 'Keyboard', price: 70 } // ]
Explanation:
These examples demonstrate how the rest and spread operators can simplify code and improve readability in real-world scenarios like managing shopping carts and processing e-commerce orders.
Here's a breakdown of what's happening in your code:
const [first, second, third, ...rest] = [10, 20, 30, 40, 50]; console.log(first); // Output: 10 console.log(second); // Output: 20 console.log(third); // Output: 30 console.log(rest); // Output: [40, 50]
Destructuring:
Rest Operator:
This code correctly logs the individual elements first, second, and third, and also captures the remaining elements into the rest array, which contains [40, 50].
Let me know if you have any further questions or if there's anything else you'd like to explore!
Atas ialah kandungan terperinci Operator Spread dan Rest dalam Javascript dengan EXAMPLE. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!