首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数组中的第一项移动到最后一个位置

将数组中的第一项移动到最后一个位置
EN

Stack Overflow用户
提问于 2020-11-21 16:43:10
回答 2查看 47关注 0票数 0

我试图在按下按钮时移动数组的第一项的位置,我尝试使用array.push(array.shift());,但它不起作用

codesandbox

代码语言:javascript
复制
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>
  );
};
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-21 16:57:28

您正在尝试记录push方法的返回值。在你的例子中,它应该是3,因为在推送一个元素后,列表大小是3。而不是它,您需要记录该列表。

代码语言:javascript
复制
exerciseList.push(exerciseList.shift()); //this will move the top element to the bottom
console.log(exerciseList); //this will give you the updated list
票数 1
EN

Stack Overflow用户

发布于 2020-11-21 16:57:56

您记录的是错误的内容。Push将返回数组的新长度。

但是,还应重新指定exerciseList的参照,否则不会检测到更改。(我想)。因此,这可能会更好地工作:

代码语言:javascript
复制
exerciseList = [
  exerciseList.shift(),
  ...excerciseList
];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64941266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档