写一个ts函数判断是否以某些特定字符串开头或结尾接收3个参数:待测字符串特定字符串string以其开头还是结尾boolean默认参数为true返回特定字符串的下标
以下是一个用 TypeScript 编写的函数,用于判断一个字符串是否以某些特定字符串开头或结尾,并返回特定字符串的下标:
function checkString(str: string, specificStrings: string[], isStart: boolean = true): number {
for (let i = 0; i < specificStrings.length; i++) {
if (isStart && str.startsWith(specificStrings[i])) {
return i;
}
if (!isStart && str.endsWith(specificStrings[i])) {
return i;
}
}
return -1; // 如果不符合条件,则返回 -1 表示没有找到特定字符串
}
使用示例:
const str = "Hello, World!";
const specificStrings = ["Hello", "Hi", "World"];
const startIndex = checkString(str, specificStrings, true);
console.log(startIndex); // 输出 0,表示以 "Hello" 开头
const endIndex = checkString(str, specificStrings, false);
console.log(endIndex); // 输出 2,表示以 "World" 结尾
注意:在 TypeScript 中,你需要使用编译器将 TypeScript 代码转换为 JavaScript 代码,然后在浏览器或 Node.js 等环境中运行 JavaScript 代码
原文地址: https://www.cveoy.top/t/topic/h6uF 著作权归作者所有。请勿转载和采集!