我试图在按下按钮时移动数组的第一项的位置,我尝试使用array.push(array.shift());,但它不起作用
import React from "react";
const DailySchedule = () => {
let exerciseList = ["exercise 1", "exercise 2", "exercise 3"];
return (
<div>
<section>
<h2>Warm-up</h2>
<ul>
{exerciseList.map((exrcs, idx) => {
return (
<li>
{exrcs}{" "}
{idx === 0 && (
<button
onClick={() =>
console.log(exerciseList.push(exerciseList.shift()))
}
>
Done
</button>
)}
</li>
);
})}
</ul>
</section>
</div>
);
};发布于 2020-11-21 16:57:28
您正在尝试记录push方法的返回值。在你的例子中,它应该是3,因为在推送一个元素后,列表大小是3。而不是它,您需要记录该列表。
exerciseList.push(exerciseList.shift()); //this will move the top element to the bottom
console.log(exerciseList); //this will give you the updated list发布于 2020-11-21 16:57:56
您记录的是错误的内容。Push将返回数组的新长度。
但是,还应重新指定exerciseList的参照,否则不会检测到更改。(我想)。因此,这可能会更好地工作:
exerciseList = [
exerciseList.shift(),
...excerciseList
];https://stackoverflow.com/questions/64941266
复制相似问题