Unexpected behavior of bound function

折月煮酒 提交于 2021-02-10 20:37:49

问题


Tried to create a function mapping numeric characters (i.e. '0' to '9') to true and other characters to false:

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

isNumeric('1') and isNumeric('0') returned true. Expected ['1', '0'].every(isNumeric) to be true too but it turned out to be false.

Something I'm missing?

This was on node v10.16.3


回答1:


includes has a second parameter called position which is the position within the string at which to begin searching. every, like every other array prototype methods, provides the index as the second argument to the callback provided. So, the code ends up being something like this:

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

Here's a snippet:

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


来源:https://stackoverflow.com/questions/58831999/unexpected-behavior-of-bound-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!