javascript - 绑定(bind)函数的意外行为

标签 javascript node.js currying

试图创建一个将数字字符(即“0”到“9”)映射到 true 并将其他字符映射到 false 的函数:

const isNumeric = String.prototype.includes.bind('0123456789');

isNumeric('1')isNumeric('0') 返回 true。 预期 ['1', '0'].every(isNumeric) 也为真,但结果为假。

我缺少什么?

这是在 Node v10.16.3 上

最佳答案

includes 有一个名为 position 的第二个参数,它是字符串中开始搜索的位置。 every 与所有其他数组原型(prototype)方法一样,提供索引作为所提供回调的第二个参数。所以,代码最终是这样的:

const exists = ['1', '0'].every((n, i) => isNumeric(n, i))

// Which translates to
// Look for "1" starting from index 0. It is found
// Look for "0" starting from index 1. Fails because "0" is at index 0
 const exists = ['1', '0'].every((n, i) => '0123456789'.includes(n, i))

这是一个片段:

const isNumeric = String.prototype.includes.bind('0123456789'),
      numbers = Array.from('149563278'); // array of numbers in random order

console.log( numbers.every(isNumeric) ) // false

console.log( numbers.every(n => isNumeric(n)) ) // true

关于javascript - 绑定(bind)函数的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58831999/

相关文章:

javascript - 在事件类标题颜色更改(添加/删除类)

javascript - 谷歌地图 API V3 信息窗口错误 : "infowindow not defined"

node.js - 无服务器框架无法识别 tsconfig 的路径

node.js - 漂亮没有在 fastify Pretty print 中定义

javascript - 与 Javascript Date 对象混淆

javascript - 如何使用 Vanilla Js 进行切换

methods - 在 Python 3 中将方法分配给 var 时如何自动使用 self currying?

programming-languages - Scheme 中 Curried 函数的实现

JavaScript 在 Node.js 中无法获取函数返回值

javascript - 回调,错误 : is not a function