繁体   English   中英

为什么代码返回一个带有单个字母而不是全名的数组?

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

学习 Javascript 中的解构分配以及尝试在 object 中解构数组时,只有第一个字母返回控制台,为什么会这样?

 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);

在此处输入图像描述

我们先来看一个简单的例子,你只是在解构数组

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

记住strings在 JS 中是可迭代的

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

所以当你这样做时

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

那么这意味着您也在从fName字符串中解构,这将导致firstChar

所以上面的内容完全一样:

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);

发生这种情况是因为splitter返回fNamelName ,它们中的每一个都是一个单词、字符串,它是一个字符数组。

当您将fName重组为数组时,它会为您提供数组中的第一个字母。

如果您将更多参数添加到数组中,您将获得字母的 rest。

要解决您的问题,请不要重组为数组。

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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