在函数中使用.includes方法

the*_*ide 10 javascript

我有一个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")
Run Code Online (Sandbox Code Playgroud)

但是,当我使用该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
Run Code Online (Sandbox Code Playgroud)

为什么会这样,是否有解决方法?

Sat*_*pal 15

您可以使用String.indexOf()而不是String.includes,因为它在ES6中可用而在IE中根本不受支持.

typeof value == "string" && value.indexOf('$') > -1
Run Code Online (Sandbox Code Playgroud)

另请注意,如果value不是字符串类型,它仍会引发错误boolean,Number不是该方法.您可以使用它typeof来验证是否value为字符串.


Sam*_*Toh 13

.includes()API是的一部分StringArray数据类型。

因此,错误试图告诉您的是 variable 的值value(例如整数或对象)没有属性.includes

你可以做检查

  1. typeof a_string === 'string'
  2. an_array instanceof Array

.includes()api之前,以防止这种情况。

显然,由于您拥有的检查数量,这会使您的 if 语句变得相当难看。

根据您编写代码的方式,我怀疑您对检查“字符串”比检查数组更感兴趣。所以要小心数组。如果它是数组,您的代码可能无法正常工作。

无论如何,这是您代码的折射版本。

function replacer(key, value) {
   // Filtering out properties
   if (!value || typeof value === "string" && value.includes("$")) {
        return undefined;
   }
   return value;
 } 

console.log("NULL returns:" + replacer('test', null));
console.log("$Test returns:" + replacer('test', '$test'));
console.log("Blah returns:" + replacer('test', 'Blah'));
Run Code Online (Sandbox Code Playgroud)


tso*_*ohr 6

还有一种可能性:也许你的value不是字符串类型对象。

(typeof(value) == "string" && value.includes("$"))