Javascript 在函数中使用 .includes 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41820770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:39:53  来源:igfitidea点击:

Using .includes method in a function

javascript

提问by the_darkside

I have a an object jsonRes[0]containing values which need to be removed based on a condition. The following works to remove null, missing values and those equal to zero in the stringified object:

我有一个jsonRes[0]包含需要根据条件删除的值的对象。以下工作用于删除null字符串化对象中的 、缺失值和等于 0 的值:

function replacer(key, value) {
          // Filtering out properties
          if (value === null || value === 0 || value === "") {
            return undefined;
          }
          return value;
        } 

JSON.stringify(jsonRes[0], replacer, "\t")

However, when I add a condition using the the includesmethod, I receive an error:

但是,当我使用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

Why is this the case and is there a workaround?

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

回答by Satpal

You can use String.indexOf()instead of String.includes, As it is available in ES6 and not supported in IE at all.

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

typeof value == "string" && value.indexOf('$') > -1

Also note if valueis not string type it will still raise an error boolean, Numberdoesn't the the method. You can use typeofto validate whether valueis a string.

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

回答by Samuel Toh

The .includes()API is part of the Stringand Arraydata type.

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

So what the error is trying to tell you is that the value for variable value, e.g. an integer or object, does not have the property .includes.

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

You could do checks like

你可以做检查

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

before the .includes()api to prevent this.

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

Obviously this will make your if statement rather ugly due to the number of checks you have.

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

Based on the way your code is written I suspect you are more interested in checking "String" than array. So becarefulof arrays. Your code may not work properly if it is array.

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

Anyway here is a refractored version of your code.

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

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'));

回答by tsohr

Just one more possibility: Maybe your valueis not a string type object.

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

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

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

回答by IzumiSy

I actually am not sure what type of the variable named valueis, but anyway, Array.prototype.includesand String.prototype.includesare only available in ES6. You need to use babel-polyfillor any other bundling modules like rollup.js, webpackwith babel or something like that to use includesfunction.

我实际上不确定命名的变量value是什么类型,但无论如何,Array.prototype.includes并且String.prototype.includes仅在 ES6 中可用。您需要使用babel-polyfill或任何其他捆绑模块,如rollup.js, webpackbabel 或类似的东西才能使用includes功能。

回答by apswrk

I solved this error, which I was getting when applying "includes" to a "window.location" value, by appending ".toString();"

我通过附加“.toString();”解决了这个错误,这是我在将“includes”应用到“window.location”值时遇到的错误。

var requestUrl = window.location.toString();

var requestUrl = window.location.toString();

if (requestUrl.includes(urlBase + "#")) { ...

if (requestUrl.includes(urlBase + "#")) { ...