gpt4 book ai didi

JavaScript 数据类型

转载 作者:搜寻专家 更新时间:2023-11-01 04:25:08 25 4
gpt4 key购买 nike

据我所知,JavaScript 没有 intsfloats,只有 Number 类型,它被格式化为 double 64 位浮点值,但 JavaScript 也有 typed arrays它可以是多种类型,包括:Int32ArrayUint32ArrayFloat32Array

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

最佳答案

So my question is: do typed arrays underneath just use the Number type with some bit operation wrapper functions, or does it actually use some other data type?

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

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

JavaScript number 数据类型是 double float 。因此它可以很好地表示较小的数据类型。但是它不能表示 64 位整数,因为它本身就是一个 64 位 float 。这就是我们没有 Int64ArrayUint64Array 的原因。

And if they do use some other type, then is it possible to actually create your own int and float types by wrapping typed arrays.

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

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);

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

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

defclass函数定义如下:

function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}

一切都放在一起:

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);

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

alert(a + " + " + b + " = " + c);

function defclass(prototype) {
var constructor = prototype.constructor;
constructor.prototype = prototype;
return constructor;
}

关于JavaScript 数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25172671/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com