JavaScript数据类型

Viv*_*vek 5 javascript arrays types number-formatting

根据我的理解,JavaScript没有整数浮点数,而只是一个数字类型,它被格式化为双精度64位浮点值,但JavaScript也有类型数组,可以是多种类型,包括:Int32Array,Uint32Array,和Float32Array.

所以我的问题是:下面的类型化数组只使用带有一些位操作包装函数的Number类型,还是实际使用其他一些数据类型?如果它们确实使用了其他类型,那么是否可以通过包装类型化数组来实际创建自己的intfloat类型.

Aad*_*hah 3

所以我的问题是:下面的类型化数组是否只使用Number类型和一些位操作包装函数,或者它实际上使用其他一些数据类型?

类型化数组不使用number类型。例如,new Int32Array(10)将创建一个包含 10 个 32 位整数的数组。因此,它确实会为您的数组分配40字节空间。

在内部,您存储在数组中的任何整数只会占用 32 位(4 字节)的空间。然而,当读取数据时,int 将被强制转换为 JavaScript number(原语,而不是对象 - 因此不大写)。因此无法将 int 读入 JavaScript。

JavaScriptnumber数据类型是双精度浮点数。因此它可以很好地表示较小的数据类型。然而它不能表示 64 位整数,因为它本身就是一个 64 位浮点数。这就是我们没有 aInt64Array或 a的原因Uint64Array

如果他们确实使用其他类型,那么是否可以通过包装类型化数组来实际创建您自己的intfloat类型。

对的,这是可能的。但是,您必须定义自己的加法、减法、强制转换等函数。例如,这就是我要做的:

var Num = defclass({
    constructor: function (array) {
        this.constructor = function () {
            this.array = new array(arguments);
        };

        return defclass(this);
    },
    toValue: function () {
        return this.array[0];
    },
    toString: function () {
        return this.array[0];
    },
    plus: function (that) {
        return new this.constructor(this + that);
    }
});

var Int8 = new Num(Int8Array);
var Uint8 = new Num(Uint8Array);
var Int16 = new Num(Int16Array);
var Uint16 = new Num(Uint16Array);
var Int32 = new Num(Int32Array);
var Uint32 = new Num(Uint32Array);
var Float32 = new Num(Float32Array);
var Float64 = new Num(Float64Array);
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使用它:

var a = new Int32(Math.pow(2, 31) - 1); // 2147483647
var b = new Int32(1);
var c = a.plus(b);                      // -2147483648
Run Code Online (Sandbox Code Playgroud)

defclass函数定义如下:

function defclass(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}
Run Code Online (Sandbox Code Playgroud)

一切放在一起:

var Num = defclass({
    constructor: function (array) {
        this.constructor = function () {
            this.array = new array(arguments);
        };

        return defclass(this);
    },
    toValue: function () {
        return this.array[0];
    },
    toString: function () {
        return this.array[0];
    },
    plus: function (that) {
        return new this.constructor(this + that);
    }
});

var Int8 = new Num(Int8Array);
var Uint8 = new Num(Uint8Array);
var Int16 = new Num(Int16Array);
var Uint16 = new Num(Uint16Array);
var Int32 = new Num(Int32Array);
var Uint32 = new Num(Uint32Array);
var Float32 = new Num(Float32Array);
var Float64 = new Num(Float64Array);
Run Code Online (Sandbox Code Playgroud)