gpt4 book ai didi

javascript - 在函数中使用 .includes 方法

转载 作者:数据小太阳 更新时间:2023-10-29 04:05:01 25 4
gpt4 key购买 nike

我有一个对象 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 不是字符串类型,它仍会引发错误 booleanNumber 不是方法。您可以使用 typeof验证 value 是否为字符串。

关于javascript - 在函数中使用 .includes 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com