问题
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