试图创建一个将数字字符(即“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/