使用要点
- 演示输出是带标签的(
dist:),每个操作都会留下自己的一行标注。
常见问题
需要安装第三方包吗?
不需要。只使用语言和平台的内建 API,粘贴进项目即可使用,无需安装任何东西。
代码示例
// sqrt 只接受非负数,负数返回 NaN 而不抛异常
console.log(Math.sqrt(16), Math.sqrt(2), Math.sqrt(-1));
// cbrt 是唯一接受负数的根函数:立方根符号随操作数
console.log(Math.cbrt(27), Math.cbrt(-8));
// pow 与 ** 等价,负底数带小数指数返回 NaN
console.log(Math.pow(2, 10), (-8) ** (1/3));
// 浮点陷阱:大数平方根可能不精确
console.log(Math.sqrt(2) ** 2 === 2, Math.sqrt(2) ** 2);
// 距离计算用 hypot 避免中间值溢出
console.log("dist:", Math.hypot(3, 4), Math.hypot(1e200, 1e200));