绑定函数的意外行为
Unexpected behavior of bound function
试图创建一个将数字字符(即“0”到“9”)映射到 true
并将其他字符映射到 false
的函数:
const isNumeric = String.prototype.includes.bind('0123456789');
isNumeric('1')
和 isNumeric('0')
返回 true
。
预计 ['1', '0'].every(isNumeric)
也是正确的,但结果是错误的。
我缺少什么?
这是在节点 v10.16.3 上
includes
有一个名为 position
的第二个参数,它是字符串中开始搜索的位置。 every
,与所有其他数组原型方法一样,提供索引作为所提供回调的第二个参数。所以,代码最终是这样的:
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
试图创建一个将数字字符(即“0”到“9”)映射到 true
并将其他字符映射到 false
的函数:
const isNumeric = String.prototype.includes.bind('0123456789');
isNumeric('1')
和 isNumeric('0')
返回 true
。
预计 ['1', '0'].every(isNumeric)
也是正确的,但结果是错误的。
我缺少什么?
这是在节点 v10.16.3 上
includes
有一个名为 position
的第二个参数,它是字符串中开始搜索的位置。 every
,与所有其他数组原型方法一样,提供索引作为所提供回调的第二个参数。所以,代码最终是这样的:
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