我正在开发一个不协调机器人,我有一个按字母顺序排列的字符数组列表。我正在尝试做的是,当有人使用$info (name)命令时,机器人将使用for循环查看数组,并从数组中抓取与字符串开头最接近的块匹配的名字。举个例子:
let namelist = ['adam', 'al', 'albert', 'bertie', 'cole'];
$info a
/*would grab Adam because he's the first on the list alphabetically
with an 'A' in his name*/
$info ber
/*would grab bertie because he's the first on the list with a ber in the
beginning of his name,
and not grab albert who has a ber later in his name and
is ahead of bertie in the array*/这就是我到目前为止所拥有的。现在,如果我尝试执行$info ber,它将获取Albert,因为它首先遇到数组中的他的名字。我考虑过使用子字符串和charAt,但我找不到一种有效的方法。我也在考虑使用findIndex或indexOf,但不知道如何使用它。
for(let i = 0; i < namelist.length; i++){
if(namelist[i].includes(name)){
object = namelist[i];
console.log(object);
break;
}
}发布于 2019-06-22 14:54:40
您可以结合使用find()和startswith()从排序列表中获取第一个匹配项:
let namelist = ['adam', 'al', 'albert', 'bertie', 'cole'];
let s = "ber"
let found = namelist.find(item => item.startsWith(s))
console.log(found)
s = 'a'
found = namelist.find(item => item.startsWith(s))
console.log(found)
发布于 2019-06-22 14:54:35
您可以结合使用Array.find()和Array.startsWith()来获取以字符串开头的名称。由于用户在搜索时可能使用大写字母,因此在搜索字符串上使用String.toLowerCase()。
const namelist = ['adam', 'al', 'albert', 'bertie', 'cole'];
const getName = str => namelist.find(s => s.startsWith(str.toLowerCase()));
console.log(getName('a')); // admin
console.log(getName('ber')) // bertie
console.log(getName('Ber')) // bertie
发布于 2019-06-23 01:19:45
这就是我的最终代码,ty ori和mark
let words = args[0];
let object = "";
let temparray = [];
let found = namearray.find(item => {item.startsWith(args[0])});
for(let i = 0; i <= namearray.length; i++){
if(i < namearray.length && namearray[i].startsWith(words)){
object = namearray[i];
console.log(object);
break;
}
else if(i < namearray.length && namearray[i].includes(words)){
temparray.push(namearray[i]);
console.log(temparray);
}
else if(i >= namearray.length && found === undefined){
console.log(temparray[0]);
object = temparray[0];
}
}https://stackoverflow.com/questions/56713267
复制相似问题