簡體   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