我的任务是打印数据集中符合特定类别的所有个人的名字;但是,数据集是一个对象数组,以字符串形式提供全名,例如:
var dataSet = [
{
"name": "John Doe",
"age": 60,
"math": 97,
"english": 63,
"yearsOfEducation": 4
},
{
"name": "Jane Doe",
"age": 55,
"math": 72,
"english": 96,
"yearsOfEducation": 10
}
]
除了filter()、map()和reduce()之外,我不能使用任何数组类型的内置函数。
我的代码的最后一部分(从对象数组“dataSet”获取名称)如下所示:
var youngGoodMath = dataSet.filter(function(person){
return person.age < avgAge && person.math > avgMath;
});
var yGMname = youngGoodMath.map(function (person){
return person.name;
});
console.log(yGMname);
它会生成一个看起来像这样的字符串数组:
["Jane Doe", "John Doe", "Harry Potter", "Hermione Granger"]
我需要找到一种方法来生产:
["Jane", "John", "Harry", "Hermione"]
我怀疑答案在于使用 .forEach 和 .Split(),但还无法破解它......
最佳答案
您可以使用Array.map()和 String.split()来解决这个问题。基本上,您需要映射每个 fullname
到first name
,所以使用 split
通过space
每个 fullname
上的字符我们可以获得一个名称数组,该数组的第一个元素将是 first name
.
const input = ["Jane Doe", "John Doe", "Harry Potter", "Hermione Granger"];
let res = input.map(name =>
{
[first, ...rest] = name.split(" ");
return first;
});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
另一种选择是使用String.match()与 positive lookahead正则表达式,即匹配后跟 space
的起始字符序列.
const input = ["Jane Doe", "John Doe", "Harry Potter", "Hermione Granger"];
let res = input.map(name => name.match(/^.*(?=\s)/)[0]);
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
关于javascript - 如何在 JavaScript 中拆分数组内的字符串(从全名中获取名字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55577672/