首页 > 解决方案 > 函数 Number() { [native code] } JavaScript 中的错误

问题描述

我只是想用小数查看我的数字变量总数,但它不起作用。我的平台是 Oracle Apex 20.2

var model = apex.region("itemig").widget().interactiveGrid("getViews", "grid").model;
console.log(model);
var amtKey = model.getFieldKey("ORAN");
//console.log(amtKey);
var totAmt = 0;
model.forEach(function(r) {
    var n_amount = parseInt(r[amtKey], 10);

    totAmt += n_amount;
    console.log(n_amount);
});

    $s('P705_TOTALORAN',totAmt);


输出是:

function Number() { [native code] }100507580901124105

我想要的是totAmt用小数获得数字的数量。由于这个本机代码,我并没有走得太远。有人能告诉我它是什么吗?更重要的是,我可以在我的工作中完成这一部分吗?

标签: javascriptapex

解决方案


Javascript 不是类型化语言。变量的类型是使用它的值来推断的。

如果你想声明变量totAmt并且n_amount是数字类型,你应该使用var/let并为它们分配一个数字:

var totAmt = 0;           // these two variables contain numbers..
var n_amount = 0;         // .. so they are of type "number"

否则,如果你这样做var totAmt = Number;,你只是分配全局对象Number,它是数字对象的本机构造函数,并且当你使用+运算符将​​它添加到另一个变量时,toString将调用该构造函数的 并产生"function Number() { [native code] }"然后连接的字符串到您的其他号码:

console.log(Number.toString());

console.log(Number + 5);

注意 1:如果要totAmt显示 2 个小数点toFixed,请在显示之前使用,如下所示:

$s("P705_TOTALORAN", totAmt.toFixed(2));

注 2:如果值r[amtKey]是十进制数,则parseInt只会得到这些小数的整数部分。您也应该使用parseFloat,Number或一元运算+符来解析小数部分。此外,forEach可以用 a 代替reduce以缩短代码,如下所示:

var totAmt = model.reduce(function(sum, r) {
  return sum + Number(r[amtKey]);               // Number will keep the decimal part of the number, whereas parseInt will only get the whole-number part
}, 0);

$s('P705_TOTALORAN', totAmt.toFixed(2));

推荐阅读