跳动探索网

💻排查报错:`lastIndexOf is not a function`🤔

导读 最近在调试代码时,遇到了一个让人头疼的问题——`lastIndexOf is not a function`。😱 这个错误提示意味着你尝试调用 `lastIndexOf(...

最近在调试代码时,遇到了一个让人头疼的问题——`lastIndexOf is not a function`。😱 这个错误提示意味着你尝试调用 `lastIndexOf()` 方法的对象可能并不是字符串或者数组,而是其他类型的数据(比如数字或布尔值)。🤯

例如,如果你误操作了类似 `5.lastIndexOf('a')` 的代码,就会触发这个错误。因为数字对象根本就没有 `lastIndexOf` 方法!💡

解决方法很简单:先检查变量类型,确保它是字符串或数组。可以使用 `typeof` 或者 `Array.isArray()` 来验证。👇

```javascript

if (typeof yourVar === 'string' || Array.isArray(yourVar)) {

console.log(yourVar.lastIndexOf('target'));

} else {

console.error('变量类型不匹配!');

}

```

记住,严谨的代码审查能帮你避免很多低级错误!💪 🎉