javascript - 类型检查不起作用

标签 javascript error-handling typechecking

Object.prototype.search = function() {

    if (!(Array.isArray(this) || typeof this === 'object' || this === 'undefined')) {

        throw {
            number: 1,
            err: 'test error'
        }
    }

    var count = 0

    for (item in this) {

        if (typeof this[item] !== 'undefined' || (typeof this[item] !== 'string' && typeof this[item] !== 'number' ) ){
            count++
        }
    }

    return count - 1

}

array1 = ['x', , , 'x', , , 'x', 1, , , , , , 7, 8]

try {

    console.log(array2.search())
}

catch (e) {

    console.log('error ' + e.number)
}

是的,我知道 array2 不存在

返回'错误未定义'
类型检查不存在的 array2 对象不会触发抛出?

如何捕捉原型(prototype)方法中的错误?

最佳答案

您应该将array2 替换为array1。

Object.prototype.search = function() {
  if (!Array.isArray(this) || typeof this === 'object' || this === undefined) {
    throw {
      number: 1,
      err: 'test error'
    }
  }
  var count = 0
  for (item in this) {
    if (typeof this[item] !== undefined) {
      count++
    }
  }
  return count - 1
}

array1 = ['x', , , 'x', , , 'x', 1, , , , , , 7, 8];
try {
  console.log(array1.search());
} catch (e) {
  console.log('error ' + e.number)
}

关于javascript - 类型检查不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48765061/

相关文章:

c++ - 类型检查中的纯名称等效

javascript - 使用 jQuery 在某些 div 上更改标题文本颜色

javascript - 尝试在obj1中提取最大值的错误Javascript

r - 使用 basename 捕获导致错误的文件名值的一部分

java - "assert false;"是一个好的做法吗?

prolog - 如何在 prolog 中使用类型检查器?

validation - Node.js 数据访问层中的错误处理

javascript - Box2dweb 禁止移动

javascript - 如何让菜单按钮出现在导航栏 Materialize CSS 中?

jsp - 使用CF标准无法运行JRun HTTP 500响应错误处理程序