CoffeeScript:
Array::remove = (e) -> @[t..t] = [] if (t = @indexOf(e)) > -1
这个方法会简单地将在位置t
的元素删掉,该位置是e
被找到的索引(如果它确实被找到了t > -1
)。 Coffeescript 将其转换为:
Array.prototype.remove = function(e) {
var t, _ref;
if ((t = this.indexOf(e)) > -1) {
return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
}
};
如果您想删除所有匹配的元素并返回一个新的数组,可以使用CoffeeScript和jQuery:
Array::remove = (v) -> $.grep @,(e)->e!=v
翻译成中文:
Array.prototype.remove = function(v) {
return $.grep(this, function(e) {
return e !== v;
});
};
不使用jQuery的grep函数实现相同的功能:
Array::filterOutValue = (v) -> x for x in @ when x!=v
翻译为:
Array.prototype.filterOutValue = function(v) {
var x, _i, _len, _results;
_results = [];
for (_i = 0, _len = this.length; _i < _len; _i++) {
x = this[_i];
if (x !== v) {
_results.push(x);
}
}
return _results;
};
Array::removing
,例如smaller_array = larger_array.removing(something)
,这样就清楚地表明它返回一个新的数组。 - PeterArray::remove = (v) -> @splice i, 1 if i = @indexOf(v) > -1
- Ricardo Tomasi$.grep @,(e)->e!=v
,我再也不会考虑使用 CoffeeScript 了。可读性等于零。 - PiTheNumber