Javascript startsWith 不是我能想到的无缘无故被调用的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38813040/
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 21:53:20  来源:igfitidea点击:

startsWith is not a function getting called for no reason I can think of

javascript

提问by Samantha J T Star

I have this code:

我有这个代码:

for (var i = 0; i < value.length; i++) {
   if (typeof value[i].keyword == 'undefined' || value[i].keyword == null || value[i].keyword.startsWith(keyword)) {
      out.push(value[i]);
   }
}

I am getting an error message saying:

我收到一条错误消息说:

TypeError: r[e].startsWith is not a function at js-cf2cc68….min.js.gz:85 at fn (eval at compile (js-cf2cc68….min.js.gz:8), :4:1003) at js-cf2cc68….min.js.gz:7 at p.$digest (js-cf2cc68….min.js.gz:7) at p.$apply (js-cf2cc68….min.js.gz:7) at HTMLBodyElement. (js-cf2cc68….min.js.gz:9)

TypeError: r[e].startsWith 不是 js-cf2cc68….min.js.gz:85 的函数在 fn (eval at compile (js-cf2cc68….min.js.gz:8), :4:1003 ) 在 js-cf2cc68….min.js.gz:7 在 p.$digest (js-cf2cc68….min.js.gz:7) 在 p.$apply (js-cf2cc68….min.js.gz: 7) 在 HTMLBodyElement。(js-cf2cc68….min.js.gz:9)

How is this possible? I think I've accounted for everything.

这怎么可能?我想我已经考虑了一切。

回答by kevin ternet

value[i].keyword.startsWith("keyword") because the parameter of start with must be a string. So that will work better this way

value[i].keyword.startsWith( "keyword") 因为 start with 的参数必须是字符串。这样会更好地工作

for (var i = 0; i < value.length; i++) {
     if (typeof value[i].keyword == String(undefined) || value[i].keyword.startsWith("keyword"))
         out.push(value[i]);
}

回答by Thomas

Is there a way that I can check if it's a string rather than have it error out?

有没有办法可以检查它是否是一个字符串而不是让它出错?

checking the type?

检查类型?

var out = values.filter(v => v.keyword == null || typeof v.keyword === "string" && v.keyword.startsWith( keyword ));

or simply enforcing the type

或者只是强制执行类型

var out = values.filter(v => v.keyword == null || String(v.keyword).startsWith( keyword ));

or if you use desctructuring, you can use even this:

或者如果你使用解构,你甚至可以使用这个:

var out = values.filter({keyword: v}) => v == null || String(v).startsWith( keyword ));

I'd reccomend you to use the Array-methods instead of manually writing loops.

我建议您使用数组方法而不是手动编写循环。

  • Imo. it is a better description of your intent (good for scanning over code).

  • If this is a hot path (it's called often) the JS-optimizer can take advantage of knowing, that youre'just filtering, and optimize the code. Maybe by skipping the lots of integrity-checks for the Array it performs during your loop.

  • And if this is not a hot-path, the performance-impact of calling a function a few times will even be hard to measure, in JS.

  • 伊莫。它更好地描述了您的意图(适合扫描代码)。

  • 如果这是一个热门路径(它经常被调用),JS 优化器可以利用知道你只是过滤和优化代码的优势。也许通过跳过它在循环期间执行的数组的大量完整性检查。

  • 如果这不是一个热门路径,那么在 JS 中多次调用一个函数对性能的影响甚至很难衡量。

回答by Samra

Found a useful articleon this topic

找到有关此主题的有用文章

The three approaches for converting to string are:

转换为字符串的三种方法是:

  1. value.toString()
  2. "" + value
  3. String(value)
  1. value.toString()
  2. "" + 值
  3. 字符串值)

The point to note here is that approach # 1 doesn't work if the value is null or undefined.

这里要注意的一点是,如果值为 null 或未定义,则方法#1 不起作用。

In my case, approach # 2 for some reason did not work either so the best option would be String(value)

在我的情况下,由于某种原因,方法#2 也不起作用,所以最好的选择是 String(value)

var col = "rt_" + rows[i]["results"][r].ResultTypeID.substring(1); //did not work

var col = "rt_" + String(rows[i]["results"][r].ResultTypeID).substring(1);

回答by Proxxa

There's a definitely obvious problem.

肯定有明显的问题。

(This is entirely for people who have a problem like this one, but they don't really understand)

(这完全是针对有这种问题的人,但他们并不真正了解)

Of course, just like many others are saying, it's in the type.If you don't know what types are (You likely do if you know this advanced type of stuff, but just in case!), its simple. The primitive types are True/False, Undefined/Null, Numbers, and Strings, any stringtype that is not empty or numbers not equal to 0resulting in being trueif put through an if statementon their own. Now that we've got that out of the way, its time to talk about startsWith(). If you run console.log("Hey VSauce, Michael here.".startsWith("Hey")), it would output trueto the console due to how the string starts out with a string. If you run console.log(1234.startsWith(1)), would occur with a TypeErrordue to startsWith()requiring a string. We can tell this is a TypeErrorfrom the error output. So, the problem above (that was already answered) was that the variable keywordwasn't being defined as a string, but rather any other variable, and needed to be defined as a string

当然,就像许多其他人所说的那样,它在类型中。如果您不知道什么是类型(如果您知道这种高级类型的东西,您可能会知道,但以防万一!),这很简单。基本类型是True/ FalseUndefined/ NullNumbersStrings,任何string非空类型或数字不等于0结果是,true如果通过if statement它们自己。现在我们已经解决了这个问题,是时候谈谈startsWith(). 如果您运行console.log("Hey VSauce, Michael here.".startsWith("Hey"))true由于字符串以字符串开头的方式,它将输出到控制台。如果您运行console.log(1234.startsWith(1)), 会出现 aTypeError由于startsWith()需要一个字符串。我们可以说这是一个TypeError从错误输出。所以,上面的问题(已经回答了)是变量keyword没有被定义为字符串,而是任何其他变量,并且需要被定义为字符串

回答by Anton Bessonov

I assume value[i].keyword is a string. String.prototype.startWith is not supported in older browsers. See browser support.

我假设 value[i].keyword 是一个字符串。较旧的浏览器不支持 String.prototype.startWith。请参阅浏览器支持

To use it in older browsers, you can use one of existing polyfills. See also answers from How to check if a string “StartsWith” another string?

要在较旧的浏览器中使用它,您可以使用现有的polyfills 之一。另请参阅如何检查字符串“StartsWith”是否为另一个字符串的答案