[英]CoffeeScript: Initialize or increment value in array
My application has different types of data about a fixed set of countries, kept in arrays of a consistent order. 我的应用程序具有有关一组固定国家的不同类型的数据,并以一致的顺序排列。
data =
oranges: [1,2,3]
apples: [1,2,3]
cabbages: [1,2,3]
These arrays get combined by various criteria into new arrays, and I find myself wanting to write code like this: 这些数组通过各种条件组合成新的数组,我发现自己想编写如下代码:
fruit = []
for key, arr of data # For each array
if key in ['oranges', 'apples'] # It it meets certain criteria
for val, i in arr # Use the values in the creation of a new array
fruit[i] += val
This doesn't work because if fruit[i]
is not initialized +=
won't work. 这不起作用,因为如果未初始化
fruit[i]
则+=
将不起作用。
There are various ways around this. 有多种解决方法。
1) Fill the new fruit
array with zeros first: 1)首先用零填充新的
fruit
数组:
for i in [0..len]
fruit[i] = 0
2) Check if fruit[i]
exists: 2)检查
fruit[i]
存在:
if fruit[i]?
fruit[i] += val
else
fruit[i] = val
Neither of these seem elegant. 这些似乎都不优雅。 I tried extracting approach 2) into a function but I have to admit that I couldn't quite get my head round it.
我尝试将方法2)提取到函数中,但是我不得不承认我不太了解它。 I thought about passing in
fruit
, cloning it (with arr.slice(0)
) and then setting fruit
to the output, but it didn't feel right to do this on every iteration. 我考虑过传入
fruit
,将其克隆(使用arr.slice(0)
),然后将fruit
设置为输出,但是在每次迭代中这样做都是不合适的。
The data format is fixed, but other than that my question is "what is the best way of handling this?" 数据格式是固定的,但除此之外,我的问题是“处理此问题的最佳方法是什么?” I'm open to answers that use CoffeeScript and/or ECMAScript 5 and/or JQuery.
我愿意接受使用CoffeeScript和/或ECMAScript 5和/或JQuery的答案。
You can initialize element of the array with using ||=
or ?=
operator: 您可以使用
||=
或?=
运算符来初始化数组的元素:
fruit[i] ||= 0
fruit[i] += val
The only difference is that ?=
checks for null
or undefined
and ||=
checks for any false
value. 唯一的区别是
?=
检查是否为null
或undefined
而||=
检查是否为false
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.