gpt4 book ai didi

javascript - 有没有正确的方法来发现 js 中的非 fatal error ?

转载 作者:行者123 更新时间:2023-11-29 14:42:36 25 4
gpt4 key购买 nike

我是调试 js 的新手。这是我玩 js 的第一周,我正在通过 D3.js 学习它。我有几年的 python 娱乐经验。

我在这里将一个值 d 传递给匿名函数。例如,想象一下 d == [55, 601]

circles.attr({
cx: function(d) { return xScale(d[0]) },
cy: function(d) { return yScale(d[1]) },
r: function(d) { return rScale( d[1] ) },
fill: function(d) { return colorScale(d) } <<<< Attention here.
});

Javascript 没有返回任何错误。圆圈使用正确的 cxcy 以及 r 值呈现,但带有 fill="#NaNNaNNaN"。但是 chrome 调试工具给了我:

> colorScale(500)
< "#7d0082"

当我在 python 中执行此操作时,我得到:

TypeError: input expected at most 1 arguments, got 2

回到 js,经过 1.5 小时的调试后,我发现将 parseInt(d) 传递给函数是有效的。但这不是答案。这是答案:

    fill: function(d) { return colorScale(d[0]) }  <<<< Fixed.

我的问题:

  • 代码运行并且没有给我一个错误。此行为是否来自 javascript、D3 或 chromium 网络工具?
  • 这种错误会在任何地方引发错误消息吗?

最佳答案

The code ran and did not give me an error. Does this behavior come from javascript, D3 or chromium web tools?

它是javascript(实际上是ECMAScript,它是底层编程语言)。

Does this kind of mistake raise an error message anywhere?

这取决于。例如,如果该函数需要一个数组但得到一个原语并尝试使用数组方法,您将得到一个错误,例如

// @param {Array} arr
// @returns arr
function foo(arr) {
arr.push('bar');
return arr;
}

// Call with an array
document.write(foo([])) // bar

// Call with a primitive instead
document.write('<br>' + foo(6)) // In console: Uncaught TypeError: arr.push is not a function

但如果您只是尝试访问命名属性,则不行。由于 ECMAScript 有助于将值强制转换为适合操作的类型,因此:

var x = 3;
alert(x.length); // undefined

原始值被暂时强制转换为对象以获取其length 属性。因为它没有,所以返回 undefined。尝试:

alert(x.toString); // function() { [native code] }

这“有效”是因为 Numbers 有一个 toString 方法继承自 Number.prototype

关于javascript - 有没有正确的方法来发现 js 中的非 fatal error ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36758630/

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