有没有正确的方法来发现 js 中的非致命错误?

Is there a correct way to spot non-fatal errors in js?

我是调试 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 没有 return 任何错误。圆圈使用正确的 cxcyr 值渲染,但使用 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.

我的问题:

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

原始值被暂时强制为一个对象以获得它的长度属性。由于它没有,因此返回 undefined。尝试:

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

其中 "works" 因为 Numbers 有一个 toString 方法继承自 Number.prototype.