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!
相关推荐
鼓掌MVP16 小时前
华为云码道实战:用 CodeArts Agent + 智能化搜索工具 API 调用自主开发「非遗文旅宣传卡生成器」
前端·人工智能·ai·html·ai编程·ai智能体·ai自动化
fengkai454516 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
不要试图纠正别人17 小时前
1055 个文件,共享 0 字节:pnpm 硬链接的静默降级
前端·node.js
tryCbest17 小时前
Vue系列——第 24 篇:VueUse——组合式工具集的百宝箱
前端·vue.js
GuWenyue17 小时前
setInterval 里的 state 永远是 0?我把 React 闭包陷阱的 5 个反例全写了一遍
前端·react.js
Xeni17 小时前
从「会写」到「真懂」:SSE 流式输出的 20 行代码与 7 个坑
前端
bai27317 小时前
字段一个不差,md5 却对不上:对象键顺序的三条规则
前端·javascript
bai27317 小时前
13 个文件名里 4 个打不开:Node 能建、cmd 和 PowerShell 却读不了
javascript·后端
map_3d_vis17 小时前
百度地图 2.0 / 3.0 项目升级到 JSAPI 4.0:改一个参数
前端·javascript·地图·百度地图
亿元程序员18 小时前
别人家的蚂蚁搬家游戏一周赚1.6万?我反省了一下我的...
前端