Ember推送范围到阵列

时间:2018-05-10 11:21:01

标签: javascript arrays ember.js

我的模板“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')
})

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

3 个答案:

答案 0 :(得分:5)

我知道已有一个已接受的答案,但是,没有真正的理由使用循环进行此类处理。 Ember对切片方法进行原型设计,该方法从给定的开始和结束索引中提取数组的子部分。您可以使用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);
})

答案 1 :(得分:2)

很抱歉给你举个例子:

你可以:

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')
})

答案 2 :(得分:-2)

试试吧:

:)

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)