每次运行后更正当前状态

时间:2019-06-23 18:07:17

标签: javascript

我有一个数组,其中有一个 product ,一个 url 和一个 state

我想通过一个while循环运行它,每次运行仅获取具有state = true的对象。

当前我无休止地运行:

const product = ['Product 1', 'Product 2']

const res = []
for (let i = 0; i < product.length; i++) {
  res.push({
    product: product[i],
    url: 'price',
    state: false,
  }, {
    product: product[i],
    url: 'groceries/',
    state: false,
  }, {
    product: product[i],
    url: 'car',
    state: false,
  }, {
    product: product[i],
    url: 'automotive/',
    state: false,
  }, {
    product: product[i],
    url: 'computer/',
    state: false,
  })
}

function setState(res, state) {
  res.state = state
}

function getState(res) {
  return res.state
}

let currentState = res.filter(el => el.state = true)
let i = 0
while (currentState.length > 0) {
  currentState = res.filter(el => el.state = true)
  this.setState(res[i], false)
  console.log(`Set state to false for ${JSON.stringify(res[i])}`)
  console.log(currentState.length)
  i++
}

有没有建议如何仅获取state = true所在的对象并在每次运行后将状态设置为true,以使我的循环终止?

感谢您的答复!

3 个答案:

答案 0 :(得分:2)

这是您使用=而不是==以及您过早重新检查状态的两个问题

还应该注意,您真的不需要== true,它可以是res.filter(el => el.state)

def insert_many():
    engine = create_engine('mysql://test_user:test@localhost/temperature',
                                  echo = True)    
    mysql_table.drop(engine, checkfirst = True)
    mysql_table.create(engine)
    conn = engine.connect()
    stmt = text("INSERT INTO temperature VALUES( STR_TO_DATE(:time, '%Y-%m-%dT%H:%i:%S.%f000Z'), :temperature)")
    conn.execute(stmt, temp_data)

答案 1 :(得分:1)

您的问题是,您使用=(赋值运算符)而不是比较运算符=====将所有元素的状态都设置为true。

在您的特定情况下,看起来好像不需要任何一个,因为el.state仍然是布尔值,因此您可以执行res.filter(el => el.state)

答案 2 :(得分:1)

您正在做

array.filter(e1 => e1.state = true)

e1.state = true将e1.state的值分配为true,并返回分配的值。

过滤器返回那些返回true的元素。

由于每个元素状态都被分配为true,并且始终返回true,所以它返回相同的数组而不是对其进行过滤。

使用

array.filter(e1 => e1.state == true)