You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中遍历Math对象的所有方法?

如何遍历JavaScript中Math对象的所有方法

Math对象的大部分方法都是不可枚举的属性,而Object.entries()仅会返回对象自身的可枚举属性,因此直接调用它会得到空数组。要遍历Math的所有方法,你可以用以下几种方式:

方法一:使用Object.getOwnPropertyNames()

该方法会返回对象自身的所有属性名(包括不可枚举属性,但不包含Symbol属性),再通过过滤筛选出函数类型的方法:

// 获取Math的所有自身属性名
const mathPropertyNames = Object.getOwnPropertyNames(Math);
// 过滤出函数类型的方法
const mathMethods = mathPropertyNames.filter(prop => typeof Math[prop] === 'function');

// 遍历所有方法
for (const methodName of mathMethods) {
  const method = Math[methodName];
  console.log(`方法名:${methodName}`, method);
}

方法二:使用Reflect.ownKeys()

该方法会返回对象自身的所有属性名,包括不可枚举属性和Symbol属性,同样过滤出函数即可:

const allMathKeys = Reflect.ownKeys(Math);
const mathMethods = allMathKeys.filter(key => typeof Math[key] === 'function');

// 遍历输出
mathMethods.forEach(methodName => {
  console.log(methodName, Math[methodName]);
});

这两种方式都能获取到Math对象的所有方法,比如Math.abs、Math.sin、Math.max等,同时排除Math.PI、Math.E这类非函数属性。

内容的提问来源于stack exchange,提问作者Ahmed Rabie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:00:56