Javascript 为什么控制台告诉我 .filter 不是函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37780950/
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
Why does console tell me that .filter is not a function?
提问by Eric Zayas
var str = "I am a string.";
console.log(str.split(''));
var fil = function(val){
return val !== "a";
};
console.log(str.filter(fil));
When I run this, it says the str.filter is not a function.
当我运行它时,它说 str.filter 不是一个函数。
回答by ali404
Because filter
is an array function (Array.prototype.filter
), while you are calling it on a string. str.split
returns an array and doesn't change anything to your str
. call it like console.log(str.split('').filter(fil))
and it should be fine.
因为filter
是一个数组函数 ( Array.prototype.filter
),而您在字符串上调用它。str.split
返回一个数组并且不会对您的str
. 称之为喜欢console.log(str.split('').filter(fil))
,应该没问题。
回答by tempoc
Because you're invoking the execution of "filter" on str, which is an object without a function called "filter" of its own nor by prototype. Since filter is not present the property's value is undefined, which cannot be invoked because its type is not function.
因为您在 str 上调用“过滤器”的执行,它是一个对象,它本身没有称为“过滤器”的函数,也没有原型。由于过滤器不存在,属性的值是未定义的,不能调用,因为它的类型不是函数。
回答by Neil DCruz
The String object does not have a filter method and String is immutable.
So in effect str.split('')
does not change the value of the string but returns a new String which you are not capturing in a variable.
String 对象没有过滤器方法并且 String 是不可变的。因此,实际上str.split('')
不会更改字符串的值,而是返回一个您未在变量中捕获的新字符串。
Try,
尝试,
console.log(str.split('').filter(fil));