【问题标题】:How to find out the number of arguments passed when creating an instance of a class? [duplicate]创建类的实例时如何找出传递的参数数量? [复制]
【发布时间】:2023-03-18 15:37:01
【问题描述】:

我需要自定义错误。如果参数不是数字并且参数 alength 大于或小于 2,则会发生错误。

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.isNum();
    }
    isNum() {
        if(typeof this.x !== 'number' || typeof this.y !== 'number' ) {
            throw new Error('point is not a number ')
        }
      console.log(arguments.length)
    } 
} 

try{
    let example = new Point(1,2)
} catch(e){ 
    console.error(e)
}
console.log(example.arguments.length)

我如何知道参数的长度?

这个拼写错了吗?

如果你能说明如何正确解决?

如果我写错了问题,我深表歉意。

【问题讨论】:

    标签: javascript exception error-handling


    【解决方案1】:

    使用arguments 对象

    注意: example 在 try 中定义,let 不能从范围外访问

    class Point {
      constructor(x, y) {
        this.x = x;
        this.y = y;
        this.arguments = arguments;
        this.isNum();
      }
      isNum() {
        if (this.arguments.length != 2) {
          throw new Error('you send more arguments')
        }
        if (typeof this.x !== 'number' || typeof this.y !== 'number') {
          throw new Error('point is not a number ')
        }
      }
    }
    
    try {
      let example = new Point(1, 2)
      console.log(example.arguments.length)
    } catch (e) {
      console.error(e)
    }

    【讨论】:

    • 如何在 isNum 中添加参数的长度以编写 if 条件?
    • 只需将isNum()中的arguments.length更改为this.arguments.length
    • 这不起作用我试过了。我是这样写的。它有效,但它是对的吗? ```this.isNum(参数); isNum(a) { if(a.length > 2 || a.length
    • @incognita 检查更新的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2013-06-23
    相关资源
    最近更新 更多