在 JavaScript 中将全名拆分为名字和姓氏
在 JavaScript 中将全名拆分为名字和姓氏:
-
对字符串调用
String.split()
方法,按空格拆分。 -
String.split()
将返回一个包含名称的数组。 - 使用数组解构将名字和姓氏的值分配给变量。
const fullName = 'Adam Jones';
// 👇️ ['Adam', 'Jones']
const [first, last] = fullName.split(' ');
console.log(first); // 👉️ Adam
console.log(last); // 👉️ Jones
我们使用
String.split
方法获取包含名称的数组。
我们在空格上拆分字符串以获取结果数组中名称的值。
我们使用数组解构来分配给同一行上的第一个和最后一个变量。
一种简单的思考方式是,第一个和最后一个变量被分配了第一个和第二个数组元素的值。
或者,我们可以在分配给变量时手动访问数组元素。
const fullName = 'Adam Jones';
// 👇️ ['Adam', 'Jones']
const splitOnSpace = fullName.split(' ');
console.log(splitOnSpace);
const first = splitOnSpace[0];
const last = splitOnSpace[1];
console.log(first); // 👉️ Adam
console.log(last); // 👉️ Jones
我们不使用数组解构,而是通过索引查找分配第一个和最后一个变量。
如果我们存储的全名包含 3 个名字,则概念相同。
下面是拆分包含 3 个名称的全名并将值分配给变量的示例:
const fullName = 'Adam Douglas Jones';
const [first, middle, last] = fullName.split(' ');
console.log(first); // 👉️ Adam
console.log(middle); // 👉️ Douglas
console.log(last); // 👉️ Jones
这是相同的示例,但使用索引查找。
const fullName = 'Adam Douglas Jones';
// 👇️ ['Adam', 'Douglas', 'Jones']
const splitOnSpace = fullName.split(' ');
const first = splitOnSpace[0];
const middle = splitOnSpace[1];
const last = splitOnSpace[2];
console.log(first); // 👉️ Adam
console.log(middle); // 👉️ Douglas
console.log(last); // 👉️ Jones
我们选择哪种方法是个人喜好的问题。 我会继续使用数组解构,因为我发现它更简洁且可读性更强。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。