我有一个对象 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
为什么会这样,是否有解决方法?
原文由 the_darkside 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
String.indexOf()
而不是String.includes
,因为它在 ES6 中可用,而在 IE 中根本不支持。另请注意,如果
value
不是字符串类型,它仍会引发错误boolean
,Number
不是该方法。您可以使用typeof
来验证value
是否是一个字符串。