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/