[英]Unexpected behavior of bound function
試圖創建一個 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
,它是開始搜索的字符串中的 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.