【问题标题】:Closest thing to an "int" in JSJS中最接近“int”的东西
【发布时间】:2020-08-13 15:51:35
【问题描述】:

我一直在尝试在 JS 中模拟 32 位有符号数字。 我希望有某种方法可以使其在语法上与 C、C++、Java 等语言相同(当然是在初始化之后)。

let a = ....
...

// Once initalized
a = 4294967296

// Should return true
console.log(a == 0)

a = Math.pow(2, 31)

// Should return false
console.log(a == Math.pow(2, 31))

我的尝试如下。我认为它非常接近,但我发现._,肯定很尴尬。有没有更好的方法可以在 JS 中模仿此类数据类型? (我也可以在window 上使用Object.defineProperties,并在全局对象上获得所需的语法,不确定这是不是更好的方法)

function int32_t(n) {
	this._value = new Int32Array([n])
	Object.defineProperties(this, {
		_: {
			get: () => this._value[0],
			set: (n) => {
				this._value[0] = n
				return this._value[0]
			},
			configurable: true
		}
	})
}
let a = new int32_t(10);

// Once initalized
a._ = 4294967296

// Should return true
console.log(a._ == 0)

a._ = Math.pow(2, 31)

// Should return false
console.log(a._ == Math.pow(2, 31))

【问题讨论】:

  • x | 0 将把 x 转换为一个 32 位有符号整数。这是你需要的吗?
  • 你可以试试打字稿
  • @VLAZ 我正在寻找一种更强大的方法来模拟“int”的行为。在为该特定变量赋值时,将自动将其转换为 int。如果可以修改它以适用于其他数据类型,包括“short”和“char”,那就太好了。
  • 是的……那会是个问题。我建议在编写自己的库之前先寻找一个库。
  • @VLAZ 正如 blz 所说,有诸如 typescript 和 dart 之类的语言可以做到这一点,但它们需要编译为 JS,这不是我想要的,而且我没有使用 node或 npm。如果有一个图书馆可以做到这一点,我会对它是如何完成的感兴趣。但是我还没有找到这样的图书馆。

标签: javascript types integer simulate


【解决方案1】:

对于任何寻求解决方案的人,这是我能得到的最接近的解决方案。 这绝对不是最优化的解决方案,因为变量必须全球化,希望将来可以改进。

function globalInt(destVar) {
  const varName = Object.keys(destVar)[0]
  const globalName = 'fakeInt_' + varName
  window[globalName] = new Int32Array([0]);
  Object.defineProperties(window, {
    [varName]: {
      get: () => window[globalName][0],
      set: (n) => {
        window[globalName][0] = n
        return window[globalName][0]
      },
      configurable: true
    }
  })
}

// Only works for globals
a = 5;

// Initalize
globalInt({a})

// Once initalized
a = 4294967296

// Should return true
console.log(a == 0)

a = Math.pow(2, 31)

// Should return false
console.log(a == Math.pow(2, 31))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 2011-08-28
    • 1970-01-01
    • 2013-01-28
    相关资源
    最近更新 更多