JS 开发问题:url.includes is not a function

  • 在 JavaScript 开发中,出现如下错误信息

    Uncaught TypeError: url.includes is not a function

问题原因
  • 这个错误是,尝试调用 url 的 includes 方法,但 url 不是一个字符串
问题复现
  1. 例如,url 是一个数字
js 复制代码
let url = 123;

if (url.includes("test")) {
    console.log("Found!");
} else {
    console.log("Not found!");
}
复制代码
# 输出结果

Uncaught TypeError: url.includes is not a function
...
  1. 例如,url 是一个对象
js 复制代码
let url = { href: "https://test.com" };

if (url.includes("test")) {
    console.log("Found!");
} else {
    console.log("Not found!");
}
复制代码
# 输出结果

Uncaught TypeError: url.includes is not a function
...
注意事项
  1. 如果 url 为 null,则会出现如下错误信息
js 复制代码
let url = null;

if (url.includes("test")) {
    console.log("Found!");
} else {
    console.log("Not found!");
}
复制代码
# 输出结果

Uncaught TypeError: Cannot read properties of null (reading 'includes')
...
  1. 如果 url 为 undefined,则会出现如下错误信息
js 复制代码
let url = undefined;

if (url.includes("test")) {
    console.log("Found!");
} else {
    console.log("Not found!");
}
复制代码
# 输出结果

Uncaught TypeError: Cannot read properties of undefined (reading 'includes')
...
处理策略
  1. 异常捕获处理
js 复制代码
try {
    let url = { href: "https://test.com" };

    if (url.includes("test")) {
        console.log("Found!");
    } else {
        console.log("Not found!");
    }
} catch (error) {
    console.log(error);
}
复制代码
# 输出结果

TypeError: url.includes is not a function
...
  1. 确保 url 是字符串
js 复制代码
let url = { href: "https://test.com" };

if (typeof url === "string" && url.includes("test")) {
    console.log("Found!");
} else {
    console.log("Not found!");
}
复制代码
# 输出结果

Not found!
相关推荐
ji_shuke8 分钟前
远程排查 Web 系统问题:如何导出 HAR 文件协助定位
前端·问题排查
AOwhisky22 分钟前
Python 学习笔记(第五期)——组合数据类型:列表、元组、集合与字典精讲——核心知识点自测与详解
开发语言·笔记·python·学习·云计算
程序员爱钓鱼36 分钟前
Rust String 与 &str 详解:字符串所有权、借用与转换
前端·后端·rust
码农学院41 分钟前
GEO与SEO协同:从传统搜索到生成式搜索的平滑迁移路径
服务器·前端·python
To_OC8 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮9 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny9 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹9 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
灯澜忆梦9 小时前
GO_并发编程---定时器
开发语言·后端·golang
阳光是sunny9 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端