具有高阶函数的字符串方法 [英] String methods with higher-order functions

查看:37
本文介绍了具有高阶函数的字符串方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试将String方法与高阶函数一起使用时,我遇到了奇怪的事情.这将引发错误:

I ran into a weird thing while trying to use String methods with higher-order functions. This will throw an error:

['a', 'b'].some('boo'.includes)

我必须将谓词包装在另一个函数中以使其起作用.但是'boo'.includes 已经不是一个函数吗?

I have to wrap the predicate in another function to make it work. But isn't 'boo'.includes already a function?

这适用于普通功能:

const boo = {
    includes: () => true
};

['a', 'b'].some(boo.includes)

String方法是否有一些特殊的属性,可以防止它们像这样构成?

Is there some special property of String methods that prevents them from being composed like this?

推荐答案

"boo" .includes 就是 String.prototype.includes .但是,在字符串"boo"上调用它会将 this 设置为"boo",这为函数提供了适当的上下文.例如."boo" .includes("b") String.prototype.includes.call("boo","b")相同.

"boo".includes is nothing else than String.prototype.includes. Calling it on the string "boo" however sets this to "boo", which gives the proper context to the function. E.g. "boo".includes("b") is the same as String.prototype.includes.call("boo", "b").

将其作为参数传递,例如 ['a','b'].some('boo'.includes),与 ['a','b'].some(String.prototype.includes),然后缺少适当的 this 作为上下文.

Passing it as an argument, e.g. ['a', 'b'].some('boo'.includes), is the same as ['a', 'b'].some(String.prototype.includes), which then lacks the proper this as context.

您当然可以使用例如 bind : ['a','b'].some(String.prototype.includes.bind("boo")),或使用可选的第二个参数thisArg some : ['a','b'].some(String.prototype.includes,"boo").这将消除错误.但是,您会注意到, some 不仅传递元素,还传递索引作为第二个参数,并将数组本身传递给第三个参数.这是一个问题,因为 includes 还将一个可选的第二个参数用作起始位置.这会导致可能的不良行为,例如数组元素"b"位于索引1,而"boo" .includes("b",1)=== false .

You can of course use e.g. bind: ['a', 'b'].some(String.prototype.includes.bind("boo")), or use the optional second parameter thisArg for some: ['a', 'b'].some(String.prototype.includes, "boo"). This will get rid of the error. However, you will then notice, that some passes not only the element, but the index as second parameter, and the array itself as third. This is a problem, as includes also takes an optional second parameter for the start position. This causes likely unwanted behavior, as e.g. the array element "b" is at index 1, and "boo".includes("b", 1) === false.

总而言之,您需要一个与 String.prototype.includes 完全不同的函数,以便将其包装到实际上可以实现所需功能的新函数中更加容易: ['a','b'].some(e =>"boo" .includes(e))

All in all, you need a function which is so different to String.prototype.includes, that it's just easier to wrap it in a new function that actually does what you want: ['a', 'b'].some(e => "boo".includes(e)), as you already noticed.

这篇关于具有高阶函数的字符串方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆