繁体   English   中英

了解JavaScript中的Number函数

[英]Understanding Number functions in JavaScript

我正在阅读Mozilla开发人员网络上的JavaScript Number对象。 我是新来的。 下面是我的脚本:

var number = 16;
console.log( Number.prototype.toExponential(number) );
console.log( Number.prototype.toFixed(number) );
console.log( Number.prototype.toPrecision(number) );
// DON'T UNDERSTAND WHAT THIS DOES
// console.log( Number.prototype.toSource(number) );
console.log( Number.prototype.valueOf(number) );  

和输出:

0.0000000000000000e+0 
0.0000000000000000 
0.000000000000000 
0   

我想知道为什么尽管number = 16却得到全零。 请帮助我理解这一点。 :)

你必须有:

var number = 16;
console.log(number.toExponential());
console.log(number.toFixed());
console.log(number.toPrecision());

使用原型,您可以定义自己的对象的方法和属性

原型基本上扩展了对象

这是一个简单的原型示例:

Number.prototype.isPrime = function() {
    if ( this === 0 || this === 1 ) {
        return false;
    }
    for ( var i = 2; i < this; i++ ) {
        if ( this % i === 0 ) {
            return false;
        }
    }
    return true;
};

var arr = [2,4,5,13,15,121];

for ( var i = 0; i < arr.length; i++ ) {
    console.log(arr[i].isPrime());
}

在此示例中, this关键字引用数字对象(因此您不必在函数中传递任何参数来进行操作)

JSFIDDLE

看看原型

Number.prototype功能住上实际数字(原型为特定类型的定义。字符串变量有住在String.prototype函数,数组对Array.prototype等定义的函数http://javascript.crockford.com /prototypal.html是学习原型继承的一个很好的起点),因此只需调用number.toFixed()number.toFixed()等。您甚至可以执行(16).toString()等。

您通过调用原型函数而不是“ on 16”来调用函数“ no on”。

如果您执行以下操作,将会获得更好的运气:

var number = new Number(16);
console.log(number.toExponential());
console.log(number.toFixed());
console.log(number.toPrecision());
console.log(number.valueOf());

注意*最好不要以这种方式在javascript中使用数字,除非您有特殊的需要避免使用基元。

之所以得到0,是因为Number原型如果未实例化,则默认为零。

Number是一个原型,在语义上被设计为用于生成继承这些方法的新对象。 这些方法的设计目的不是直接从Number原型中调用,而是从数字本身中调用。 请尝试以下操作:

(16).toExponential();

您必须将数字包装在括号中,以便解释器知道您正在访问方法而不是定义浮点。

这里要了解的重要一点是, Number原型提供了所有数字将在javascript中继承的所有方法。

为了进一步解释为什么得到0,Number原型上的方法旨在“绑定”到数字对象。 他们将使用绑定对象进行输入,并将忽略任何参数。 由于它们绑定到默认的Number对象,因此默认数字为0,因此所有方法都将返回其版本0。

在javascript中,有一种方法可以使用“调用”方法将方法重新绑定到对象(还有绑定和应用方法):

Number.prototype.toExponential.call(16);

尝试这个:

var number = 16;
console.log( Number.prototype.toExponential.call(number) );

注意call() ,该方法在实例上调用Number对象的toExponential方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM