应用 toString() 时更改的数字值 [英] Number values changing when toString() applied

查看:53
本文介绍了应用 toString() 时更改的数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在测试我的一个检查数字有效性的函数时,我注意到一些非常奇怪的事情,我在测试number.toString()[0]"时首先注意到了这一点.如果我控制台登录 (fLetter(019272));0"始终显示1".
在线检查后,我找不到与对包含0"的数字使用 toString() 方法相关的任何问题.

I am noticing something very strange when testing one of my functions that checks the validity of numbers, I first noticed it when testing the 'number.toString()[0]'. If I console logged (fLetter(019272)); the '0' is always showing '1'.
After checking online I couldn't find any issues associated with using the toString() method on numbers containing '0'.

function numberValidate(number) {

        var numCheck = [0, 5, 7, 8, 9];
        var fLetter = number.toString()[0];

        if (number.match(/^\d{6}$/)) {
            for (var i = 0; i < 5; i++) {
                if (fLetter == numCheck[i]) {
                    return false;
                } else {
                    return true;
                }
            } 
        } 

    } 

我尝试在应用和不应用 toString() 方法的情况下检查其他一些测试变量,但得到了一些我无法理解的结果.**注意 - toString() 添加产生相同的结果(在 JSfiddle 中执行)

I tried checking a few other test variables with and without applying the toString() method and got some results I couldn't understand. **Note - the toString() addition produced the same results (carried out in JSfiddle)

var numTest = 00000000;
var numTest1 = 20203020;
var numTest2 = 011000110100;
var numTest3 = 01928;
var numTest4 = 012345;

console.log(numTest);     //Returned 0
console.log(numTest1);    //Returned 20203020
console.log(numTest2);    //Returned 1207996480
console.log(numTest3);    //Returned 1928
console.log(numTest4);    //Returned Returned 5349

任何人都可以解释为什么我要返回这些值吗?谢谢

Could any one shed any light on why I am getting these values returned? Thanks

推荐答案

Number 是数字的 64 位浮点表示.它不将数字保存为字符数组,因此前导零不可用.String 保存一个字符数组,因此前导 0 不会丢失

Number is a 64bit floating point representation of a number. It does not hold the digits as a array of characters so the leading zero is not available. String holds an array of characters and thus the leading 0 is not lost

JavaScript 允许透明类型转换(如果可能),因此字符串0111"== 到数字 111.因此,如果您编写代码 "0111" == 111,它将返回 true.

JavaScript allows for transparent type conversion if possible thus the String "0111" == to the Number 111. So if you write the code "0111" == 111 it will return true.

Javascript 提供了两个相等运算符 == 和严格相等 === 第二个要求双方是相同的类型所以 Number(111) === String("111") 将返回 false,因为它们的类型不同.这同样适用于不等式运算符 != 和 !==

Javascript provides two equality operators == and the strict equality === the second requires that both side are the same type so the Number(111) === String("111") will return false as they are not the same type. The same applies for inequality operators != and !==

这篇关于应用 toString() 时更改的数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆