Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

请实现一个通用的Array解构赋值 #84

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

请实现一个通用的Array解构赋值 #84

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@kangkang123269
Copy link

let arr= [1 ,2 ,3 ,4 ];
let[a,...rest]=arr; 
// a=1 rest=[2 ,3 ,4]

@Windseek
Copy link

Windseek commented Apr 6, 2024

const targetArray = [1, [2, 3], 4];
const formater = '[a, [b], c]';
const formaterArray = ['a', ['b'], 'c'];

const destructuringArray = (values, keys) => {
try {
const obj = {};
if (typeof keys === 'string') {
keys = JSON.parse(keys.replace(/\w+/g, '"$&"'));
}

const iterate = (values, keys) =>
  keys.forEach((key, i) => {
    if (Array.isArray(key)) iterate(values[i], key);
    else obj[key] = values[i];
  });

iterate(values, keys);

return obj;

} catch (e) {
console.error(e.message);
}
};

console.dir(destructuringArray(targetArray, formater));
console.dir(destructuringArray(targetArray, formaterArray));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants