需要考虑到NaN和空数组
/**
* 判断数组中是否存在某个指定的元素
*
* @returns {boolean} 返回布尔值
*
* @example
*
* [1,2,3,1,2,NaN].hasAttr(NaN);
* //=> true
* */
function hasAttr(attr) {
//判断NaN
if (Number.isNaN(attr)){
for (let i = 0, len = this.length; i < len; i++) {
if (Number.isNaN(this[i])) {
return true
}
}
}
//判断空数组[]
if (Object.getType(attr) === 'array' && attr.length === 0){
for (let i = 0, len = this.length; i < len; i++) {
if (Object.getType(attr) === 'array' && attr.length === 0) {
return true
}
}
}
//普通元素
if (this.indexOf(attr) + 1){
return true
}
return false
}
Array.prototype.hasAttr = hasAttr;