【问题标题】:How can I cycle the values of 4 variables in Javascript?如何在 Javascript 中循环 4 个变量的值?
【发布时间】:2018-04-04 08:23:19
【问题描述】:

我有 4 个整数变量:A、B、C 和 D。

我想要一个名为 cycle() 的函数,其中 A 的值转到 B,B 的值转到 C,C 的值转到 D,D 的值转到 A。

我该怎么做?

【问题讨论】:

    标签: javascript variables integer


    【解决方案1】:

    ES6 允许您使用 destructuring assignment 来做到这一点:

    [a, b, c, d] = [b, c, d, a];
    

    ([d, a, b, c]如果“D去A”意味着A应该得到D的价值)

    【讨论】:

      【解决方案2】:

      您可以使用pushshift 来执行此操作。它将支持 N 个元素旋转。

      function cycle(arr){
              arr.push(arr.shift());
              // if you want d goes to a then 
              //arr.unshift(arr.pop());
              return arr;
          }
          
          var a = 1, b= 2, c = 3, d = 4;
          [a,b,c,d] = cycle([a,b,c,d]);
       console.log(a,b,c,d);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        • 1970-01-01
        相关资源
        最近更新 更多