使用 React hooks 反转数组

Reverse an array with React hooks

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

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

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,反之亦然。

尝试

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);

您可以使用 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];
}

你可以简单地使用 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

你可以使用数组的reverse方法

function reverse(a){
  return a.reverse()
}

console.log(reverse([true, false]))

你可以试试这个

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);