[英]Array.every returns false instead of type error
In practising various JavaScript code katas, I came across this problem: 在练习各种JavaScript代码片时,我遇到了这个问题:
Write a function isIntArray with the below signature 用以下签名编写一个函数isIntArray
function isIntArray(arr) {
return true;
}
I had made my own solution to this, but one of the accepted solutions was the following: 我已经针对此问题提出了自己的解决方案,但以下一种可接受的解决方案是:
function isIntArray(arr) {
return Array.isArray(arr) && arr.every(function (x) { return Math.floor(x)=== x });
}
Now i understand how the Math.floor section works when determining if x is a decimal, but what i don't understand is how it doesn't fall over when it encounters something like: 现在,我了解了确定x是否为小数时Math.floor部分的工作方式,但是我不明白的是,当x遇到类似以下内容时,它不会跌落:
var arr = [1,2,"asd",NaN,5];
I Tried reading through some guides on Math.floor and Array.prototype.every and i can't find anything that explains this. 我尝试阅读了有关Math.floor和Array.prototype.every的一些指南,但找不到任何可以解释这一点的内容。 Surely if x was a string then Math.floor(x) === x should return a TypeError?
当然,如果x是字符串,那么Math.floor(x)=== x应该返回TypeError?
Surely if
x
was a string thenMath.floor(x) === x
should return aTypeError
?当然,如果
x
是字符串,那么Math.floor(x) === x
应该返回TypeError
?
Nope. 不。 Most mathematical functions and operations return
NaN
if one of the operand cannot be converted into number and then operated upon. 如果其中一个操作数无法转换为数字然后再进行运算,则大多数数学函数和运算都会返回
NaN
。
So, it becomes Math.floor("asd") === "asd"
is essentially 因此,它变成
Math.floor("asd") === "asd"
本质上是
NaN === "asd" // which is obviously false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.