-
在 JavaScript 开发中,出现如下错误信息
Uncaught TypeError: url.includes is not a function
问题原因
- 这个错误是,尝试调用 url 的 includes 方法,但 url 不是一个字符串
问题复现
- 例如,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
...
- 例如,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
...
注意事项
- 如果 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')
...
- 如果 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')
...
处理策略
- 异常捕获处理
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
...
- 确保 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!