Ember框架下如何将数组指定范围元素推入目标数组?
解决Ember中根据from/to截取数组元素的问题
你的问题出在当前的forEach逻辑上——你没有判断元素是否处于from和to之间,而是在每次循环里都执行了this.get('result').push(time),这就导致整个数组的元素都被塞进了result里,再加上遇到from和to时的额外push,结果肯定不对。
下面给你两种更简洁且正确的实现方式:
方法一:利用数组的filter方法(适合元素唯一、无需严格依赖顺序的场景)
直接筛选出大于等于from且小于等于to的元素,写法直观易懂:
time: Ember.computed('from', 'to', 'formData.time', function() { const from = this.get('from'); const to = this.get('to'); const timeArray = this.get('formData.time'); // 筛选出符合范围的元素 return timeArray.filter(item => item >= from && item <= to); })
方法二:利用indexOf和slice(严格依赖数组顺序,适合截取连续片段的场景)
如果数组元素可能重复,或者需要严格截取from到to在数组中的连续片段,就先找到两者的索引,再用slice截取:
time: Ember.computed('from', 'to', 'formData.time', function() { const from = this.get('from'); const to = this.get('to'); const timeArray = this.get('formData.time'); const fromIndex = timeArray.indexOf(from); const toIndex = timeArray.indexOf(to); // 处理边界情况:如果from或to不在数组中,返回空数组 if (fromIndex === -1 || toIndex === -1) { return []; } // slice是左闭右开,所以toIndex要+1才能包含to元素 return timeArray.slice(fromIndex, toIndex + 1); })
额外注意事项:
- 把
formData.time加入计算属性的依赖项,这样原数组变化时,计算属性会自动重新计算。 - 不需要单独维护
result数组,直接返回新数组即可,这符合Ember计算属性的最佳实践,能避免状态残留问题。
内容的提问来源于stack exchange,提问作者Abdulelah
相关产品推荐
相关产品推荐

