Ember 将范围推送到数组

Ember Push Range To Array

我必须在我的模板 "from" 和 "to" 中使用变量来循环遍历 select 标记中的数据数组。

我想将 "from"、"to" 和它们之间的值推送到另一个数组。

数组是这样的

[1,2,3,4,5,6,7,8,9,0]

如果用户在 from 字段中选择“2”,在 "to" 字段中选择“6”,我想推送“2”和“6”以及它们之间的数据,所以结果将是:

[2,3,4,5,6]

我试过了

result : [],
time : Ember.computed('from', 'to', function() {
    this.get('formData.time').forEach(time => {
    // formData.time is a service from which i'm getting the array
        if (time == this.get('from')) this.get('result').push(time)
        this.get('result').push(time)
        if (time == this.get('to')) this.get('result').push(time)
    })
    return this.get('result')
})

但它推动了所有阵列,我知道我正在做的是错误的方法 但是我找不到正确的方法。

试试看:

:)

const a = [1,2,3,4,5,6,7,8,9,0]
const from = 2, to = 6
const value = []
const fromIndex = a.indexOf(from), toIndex = a.indexOf(to)
a.forEach((item, index) => index >= fromIndex && index <= toIndex && value.push(item))
console.log(value)

不好意思举个例子:

你可以:

result : [],
time : Ember.computed('from', 'to', function() {
    var from = this.get('from'), to = this.get('to')
    var fromIndex = this.get('formData.time').indexOf(from), toIndex = this.get('formData.time')
  this.get('formData.time').forEach((item, index) => index >= fromIndex && index <= toIndex && this.get('result').push(item))
  return this.get('result')
})

我知道已经有一个可接受的答案,但是,没有真正的理由对这种处理使用循环。 Ember 原型 slice 方法,它从给定的开始和结束索引中提取数组的子部分。您可以使用 MDN 作为参考。以下是如何使用切片方法的示例。

MDN:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

result : [],
time : Ember.computed('from', 'to', function() {
    var { from, to } = this.getProperties(['from', 'to']);
    var fromIndex = this.get('formData.time').indexOf(from);
    var toIndex = this.get('formData.time').indexOf(to);
    var data = this.get('formData.time').slice(fromIndex, toIndex + 1);
    return this.get('result').concat(data);
})