代码之家  ›  专栏  ›  技术社区  ›  Carol.Kar

每次运行后更正当前状态

  •  0
  • Carol.Kar  · 技术社区  · 7 年前

    我有一个数组 产品 ,一个 网址 以及 状态 是的。

    我想运行一个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++
    }

    任何关于如何只获取 状态=真 并将每次运行后的状态设置为true,以便我的循环终止?

    谢谢你的回复!

    3 回复  |  直到 7 年前
        1
  •  2
  •   racamp101    7 年前

    这里有两个问题:使用=而不是=和过早地重新检查状态

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

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

    您的问题是,通过使用 = (赋值运算符)而不是 == === 它们是比较运算符。

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

        3
  •  1
  •   Dharmendra Vaishnav    7 年前

    你在做什么

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

    e1.state=true将e1.state值指定为true并返回指定的值。

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

    因为每个元素状态都被赋值为true,并且总是返回true,所以它返回相同的数组,而不是过滤它。

    使用

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