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

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

学习 Javascript 中的解构赋值,当尝试在对象解构中使用数组时,只需第一个字母 return 来安慰,为什么会这样?

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

出现这种情况是因为splitter returns你fNamelName,每一个都是一个词,字符串,是一个字符数组。

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

如果您向数组添加更多参数,您将获得其余的字母。

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

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

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

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

所以当你这样做时

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

那么这意味着你也在解构 fName 字符串,这将导致 firstChar 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);