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!
相关推荐
子兮曰3 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰3 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
前端小万3 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝3 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋3 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
卡布鲁3 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++