假设您有一个数组,其中包含一些字符串作为某个对象的名称.现在,您必须通过java脚本找到一个包含奇数字母的字符串



const array=[‘bul’,‘abu’,‘ony’,‘buul’,‘suny’];函数{enter code here

我认为您应该使用余数运算符来确定字符串长度是否为奇数,并使用Array.prototype.find((来查找列表中的值

余数运算符(%(返回一个操作数除以第二个操作数时剩余的余数。

find((方法返回所提供数组中满足所提供测试函数的第一个元素的值。如果没有值满足测试函数,则返回undefined。

const names = ['abul','babu','rony','babul','suny']
// function that takes a string and returns true if the string has odd length
// determines whether a string's length is odd using modulo operator and checking remainder
const hasOddLength = str => str.length % 2 !== 0
// uses hasOddLength as callback for find()
const findStringWithOddLength = (list) => (
list.find(str => hasOddLength(str))
)
console.log(findStringWithOddLength(names)) // "babul"

注意:如果有多个长度为奇数的名称,find()将只返回第一个名称。

最新更新