【问题标题】:array destructuring using another array elements使用另一个数组元素进行数组解构
【发布时间】:2019-02-07 07:29:17
【问题描述】:

我有以下用户数组:

const usersArray = [ 'A', 'B'];

可以是任意长度:

const usersArray = [ 'A', 'B', 'C', 'D'];

我正在使用这些变量名提取前两个:userA 和 userB。这些变量名是已知的。

const [ userA, userB] = usersArray;

然后我在其他用户数组中获得了一些未知的用户名:

const otherUsers = [ 'userC', 'userD', 'userE'];

如何从otherUsers 内部变量名下的usersArray 中提取值?鉴于我首先需要提取已知的,然后是其他的。

更新:

我可以对前两个已知变量进行 unshift:

otherUsers.unshift('userA', 'userB')

所以现在我所有的变量都在otherUsers 中。 如何一一提取?

【问题讨论】:

    标签: javascript arrays ecmascript-6 destructuring


    【解决方案1】:

    只需使用其余属性:

     const [ userA, userB, ...otherUsers] = usersArray;
    

    或者使用slice

     const [ userA, userB] = usersArray;
     const otherUsers = usersArray.slice(2);
    

    【讨论】:

      【解决方案2】:

      你要做的就是使用eval()

      const usersArray = ['A', 'B', 'C', 'D'];
      
      const otherUsers = ['userC', 'userD', 'userE'];
      
      const allUsers = otherUsers.unshift('userA', 'userB')
      
      let joined = allUsers.join(',');
      
      eval(`let [${joined}] = usersArray`);
      

      现在如果你运行console.log(userA, userB, userC, userD, userE),你会得到定义的变量。

      注意因为eval in 不是good way 来评估一串代码,所以可以使用window.Function。只需将 eval 调用替换为 Function 调用,如下所示:

      Function(`let [${joined}] = usersArray`)
      

      【讨论】:

        猜你喜欢
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 2018-02-09
        相关资源
        最近更新 更多