gpt4 book ai didi

javascript - 如何检查数组中的项目是否为字母?

转载 作者:行者123 更新时间:2023-11-30 11:02:36 26 4
gpt4 key购买 nike

所以在 coderbyte 上有这个练习:

Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several characters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.

示例测试用例:

Input:"+d+=3=+s+"

Output:true

Input:"f++d+"

Output:false

这是我想出的解决方案,但它不起作用:

function SimpleSymbols(str) { 

// code goes here

var splitted = str.split('')
var result = splitted.map(function (arr){
for (var i=0; i<splitted.length; i++){
if (splitted[i] == '+' && splitted[i+2] == '+' && splitted[i+1] == /[a-z]/gi || && splitted[i+1] == /[A-Z]/gi){
return true
}
return false
}
}
})

return result;

}

// keep this function call here
SimpleSymbols(readline());

我认为问题在于我如何在 if 语句中编写正则表达式条件。

那么如何正确判断splitted[i+1]是一个字母呢?

最佳答案

function SimpleSymbols(str) { 

// code goes here

var splitted = str.split('')
var result = splitted.map(function (arr){
for (var i=0; i<splitted.length; i++){
if (splitted[i] == '+' && splitted[i+2] == '+' &&
(/^[a-zA-Z]+$/.test(splitted[i+1])))
{
console.log('true');
return true;
}else{
console.log('false');
return false;
}
}
})

return result;

}

SimpleSymbols('+d+=3=+s+');

关于javascript - 如何检查数组中的项目是否为字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57062270/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com