简体   繁体   中英

Why the code returning an array with a single letter instead of whole name?

Learning Destructuring assignment in Javascript and when trying to have an array in object destructuring, just first letter return to console, why it's happening?

 function splitter(name) { const [fName, lName] = name.split(" "); return { fName, lName }; } const {fName: [firstWord],lName} = splitter("John Doe"); console.log(splitter("John Doe")); console.log({fName: [firstWord],lName}); console.log(firstWord); console.log(lName);

enter image description here

Let's first take the simple case, where you are just destructuring the array

 function splitter(name) { const [fName, lName] = name.split(' '); return { fName, lName }; } const { fName, lName } = splitter('John Doe'); console.log(fName); // John

Remember the strings are iterable in JS

 const str = 'John'; for (let c of str) { // For-of can only be used in iterables console.log(c); }

So when you do

const { fName: [firstWord], lName } = splitter('John Doe');

then this means you are also destructuring from the fName string, which will result in the firstChar as

So the above is exactly same as:

const { fName, lName } = splitter('John Doe');
const [firstChar] = fName;
console.log(firstChar);

 function splitter(name) { const [fName, lName] = name.split(' '); return { fName, lName }; } const { fName, lName } = splitter('John Doe'); const [firstChar] = fName; console.log(firstChar);

This happen because splitter returns you fName and lName , each of them is a word, string, which is an array of characters.

When you restructure fName to an array, it gives you the first letter in the array.

If you will add more args to the array you will get the rest of the letters.

To fix your issue just don't restructure into an array.

 function splitter(name) { const [fName, lName] = name.split(" "); return { fName, lName }; } const {fName: [ch1,ch2,ch3,ch4],lName} = splitter("John Doe"); console.log({fName: [ch1,ch2,ch3,ch4],lName}); const {fName: [char1, ...restOfChars]} = splitter("John Doe"); console.log(char1); console.log(restOfChars); const {fName: wholeWord} = splitter("John Doe"); console.log(wholeWord);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM