You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将CoffeeScript数组内容复制到变量?新手技术问询

How to Store Processed Array Content in a Variable with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:17:29