我有一个对象 jsonRes[0]
包含需要根据条件删除的值。以下工作用于删除字符串化对象中的 null
、缺失值和等于零的值:
function replacer(key, value) {
// Filtering out properties
if (value === null || value === 0 || value === "") {
return undefined;
}
return value;
}
JSON.stringify(jsonRes[0], replacer, "\t")
但是,当我使用 includes
方法添加条件时,我收到一个错误:
function replacer(key, value) {
// Filtering out properties
if (value === null || value === 0 || value === "" || value.includes("$")) {
return undefined;
}
return value;
}
Uncaught TypeError: value.includes is not a function
为什么会这样,是否有解决方法?
最佳答案
您可以使用 String.indexOf()
而不是 String.includes
, 因为它在 ES6 中可用,而在 IE 中完全不支持。
typeof value == "string" && value.indexOf('$') > -1
另请注意,如果 value
不是字符串类型,它仍会引发错误 boolean
,Number
不是方法。您可以使用 typeof
验证 value
是否为字符串。
关于javascript - 在函数中使用 .includes 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820770/