如何将CoffeeScript数组内容复制到变量?新手技术问询
Hey there! No worries at all—we all start out confused with new languages, so this is totally a valid question 😊
Let's break down what you're trying to do. You have your pizzas array and a menu function that formats each pizza into a nice string, and you want to collect all those formatted strings into a variable instead of just running the loop without saving the output.
The Cleanest Way: Array Comprehensions (CoffeeScript's Superpower!)
CoffeeScript has awesome array comprehensions that let you generate arrays directly from loops. Here's how to adjust your code to save the results to a variable:
# Your original pizza array pizzas = ["Veggie", "Cheese", "Pepperoni", "Combo"] # Your formatting function menu = (i, pizza) -> "#{i}) #{pizza}" # Store the formatted menu items in pizzaMenu pizzaMenu = [menu(i + 1, pizza) for pizza, i in pizzas]
After running this, pizzaMenu will be an array containing your formatted strings:["1) Veggie", "2) Cheese", "3) Pepperoni", "4) Combo"]
The comprehension [menu(i + 1, pizza) for pizza, i in pizzas] tells CoffeeScript to iterate over each pizza (and its index i), run the menu function with the adjusted index (since you want 1-based numbering), and collect all those results into a new array assigned to pizzaMenu.
Alternative: Explicit Loop with Push
If you prefer a more explicit approach (great for learning!), you can initialize an empty array and push each formatted item into it:
pizzas = ["Veggie", "Cheese", "Pepperoni", "Combo"] menu = (i, pizza) -> "#{i}) #{pizza}" # Start with an empty array pizzaMenu = [] # Loop through each pizza and push the formatted string to the array for pizza, i in pizzas pizzaMenu.push(menu(i + 1, pizza))
This does the exact same thing as the comprehension—just with more explicit steps.
Quick Note: If You Just Want a Copy of the Original Array
If you ever need to make a copy of the pizzas array without modifying the items, you can do this simply:
pizzaCopy = [...pizzas] # Or using slice() pizzaCopy = pizzas.slice()
But based on your code, it looks like you want the formatted version, so the first two methods are what you need.
内容的提问来源于stack exchange,提问作者Thom

