【问题标题】:Reverse an array with React hooks使用 React 钩子反转数组
【发布时间】:2019-06-28 10:40:07
【问题描述】:

使用 javascript 有没有快速交换数组中的两个项目的方法?

所以如果它是一个布尔值,你可以这样做

const [isTrue, setIsTrue] = useState(false);

setIsTrue(!isTrue);

但是说我有一个数组

// I want to swap the items in the array on a click 
const [trueOrFalse, setTrueOrFalse] = useState([true, false]);

我想切换这些,如果有两个项目,有没有一种快速交换数组中项目的方法

setTrueOrFalse(!trueOrFalse); // would equal [false, true]

<div onClick={() => setTrueOrFalse()} />Swap items in array</div>

我正在尝试获取索引 0 处的元素并将其移动到索引 1,反之亦然。

【问题讨论】:

  • 我不明白你的问题.....请澄清
  • 您是否要反转数组中每个元素的值?如果是这样,那就是trueOfFalse.map(val =&gt; !val)。或者您是否尝试将索引 0 处的元素移动到索引 1,反之亦然?
  • 更新了我的问题@messerbill 现在更清楚了吗?
  • @NicholasTower 我正在尝试将索引 0 处的元素移动到索引 1,反之亦然
  • 我认为你应该使用useEffect,就像reactjs.org/docs/hooks-effect.html一样

标签: javascript reactjs ecmascript-6 react-hooks


【解决方案1】:

你可以简单地使用解构和 useState setter 回调方法

// I want to swap the items in the array on a click 
const [trueOrFalse, setTrueOrFalse] = useState([true, false]);

const swapState = () => {
    setTrueOrFalse(prevState => {
        const [val1, val2] = prevState;
        return [val2, val1];
    })
}

<div onClick={() => swapState()} />Swap items in array</div>

Working demo

【讨论】:

    【解决方案2】:

    试试

    let a=[true, false];
    
    // inverse values
    let b= a.map(x=>!x)
    
    // swap sequence (inplace)
    a.reverse();
    
    console.log('inverse values', b);
    console.log('swap sequence', a);

    【讨论】:

      【解决方案3】:

      您可以使用 ES6 destructuring assignment 在单个表达式中轻松交换变量:

      //Get inital array from useState and store in 2 variables
      var [val1, val2] = useState();
      
      //Check out the values
      console.log(`Before swap values: val1 = ${val1}, val2 = ${val2}`);
      
      //Do the swap using array desctructuring:
      [val1, val2] = [val2, val1];
      
      //Now see that the values have swapped
      console.log(`After swap values: val1 = ${val1}, val2 = ${val2}`);
      
      function useState() {
        return [true, false];
      }

      【讨论】:

      • 你可以反转数组,当然,但如果你总是要处理一个包含 2 个元素的数组,那么我认为这更简单。
      【解决方案4】:

      你可以使用reverse数组方法

      function reverse(a){
        return a.reverse()
      }
      
      console.log(reverse([true, false]))

      【讨论】:

        【解决方案5】:

        你可以试试这个

        Array.prototype.swap = function(index1,index2){
        	[this[index1], this[index2]] = [this[index2],this[index1]]
        }
        let arr = [1,2,3,4];
        arr.swap(1,2);
        console.log(arr);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-06-01
          • 2021-02-05
          • 1970-01-01
          • 2023-03-19
          • 2022-01-12
          • 2022-01-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多