[英]array destructuring using another array elements
I have the following users array: 我有以下用户数组:
const usersArray = [ 'A', 'B'];
it could be any length: 它可以是任何长度:
const usersArray = [ 'A', 'B', 'C', 'D'];
i am extracting the first two using these variable names: userA and userB. 我正在使用这些变量名提取前两个:userA和userB。 These variable names are known.
这些变量名是已知的。
const [ userA, userB] = usersArray;
Then i have some unknown user names that i get inside other users array: 然后我有一些我在其他用户数组中得到的未知用户名:
const otherUsers = [ 'userC', 'userD', 'userE'];
how can I extract the values from usersArray
under the variable names inside otherUsers
? 如何从
usersArray
内部变量名下的otherUsers
提取值? given that i first need to extract the known ones, then other ones. 鉴于我首先需要提取已知的,然后再提取其他。
I can do an unshift for the first two known variables: 我可以对前两个已知变量进行取消移位:
otherUsers.unshift('userA', 'userB')
so now all my variables are inside otherUsers
. 所以现在我所有的变量都在
otherUsers
内部。 how can I extract them one by one? 我怎样才能一一提取它们?
just use the rest property: 只需使用rest属性:
const [ userA, userB, ...otherUsers] = usersArray;
Or alternatively use slice
: 或者使用
slice
:
const [ userA, userB] = usersArray;
const otherUsers = usersArray.slice(2);
What you have to do is use eval() . 您要做的是使用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`);
now if you run console.log(userA, userB, userC, userD, userE)
, you would get the defined variables. 现在,如果您运行
console.log(userA, userB, userC, userD, userE)
,您将获得已定义的变量。
NB because eval in not a good way to evaluate a string of code, you can use window.Function . 注意:由于eval并不是评估代码字符串的好方法 ,因此可以使用window.Function 。 Just replace the eval call with the Function call like this:
只需将eval调用替换为Function调用,如下所示:
Function(`let [${joined}] = usersArray`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.