为什么这个 lodash 包含 return true?
Why does this lodash includes return true?
我有一个 csv 值,需要检查我的数组单元中的 csv 值之一是否可用。
为什么我在这两种情况下都为真?
let arr = [16]
let check = _.includes('14,15,16,17,18,19', arr)
console.log(check);
arr = [6]
check = _.includes('14,15,16,17,18,19', arr)
console.log(check);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
_includes
is
的签名
_.includes(collection, value, [fromIndex=0])
如果 collection
是一个字符串 - 它在这里:
If collection is a string, it's checked for a substring of value
您传递的两个值 - [16]
和 [6]
- 当强制转换为字符串时 - 作为子字符串存在。 ('16'
和 '6'
)
听起来您可能想先将字符串转换为数字数组 - 然后仅检查单个值,而不是数组。例如:
const inputString = '14,15,16,17,18,19';
const arrOfNumbers = JSON.parse(`[${inputString}]`);
console.log(arrOfNumbers.includes(16));
console.log(arrOfNumbers.includes(6));
我有一个 csv 值,需要检查我的数组单元中的 csv 值之一是否可用。
为什么我在这两种情况下都为真?
let arr = [16]
let check = _.includes('14,15,16,17,18,19', arr)
console.log(check);
arr = [6]
check = _.includes('14,15,16,17,18,19', arr)
console.log(check);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
_includes
is
_.includes(collection, value, [fromIndex=0])
如果 collection
是一个字符串 - 它在这里:
If collection is a string, it's checked for a substring of value
您传递的两个值 - [16]
和 [6]
- 当强制转换为字符串时 - 作为子字符串存在。 ('16'
和 '6'
)
听起来您可能想先将字符串转换为数字数组 - 然后仅检查单个值,而不是数组。例如:
const inputString = '14,15,16,17,18,19';
const arrOfNumbers = JSON.parse(`[${inputString}]`);
console.log(arrOfNumbers.includes(16));
console.log(arrOfNumbers.includes(6));