类数组转换

类数组转化为数组

获取页面中的类数组

var divList = document.getElementsByTagName("div");
console.log(divList); // 输出的结果HTMLCollection元素集合
var oList = document.getElementsByName("zhufeng");
console.log(oList); // 输出结果NodeList结点集合
// 将类数组转换为数组
var ary = Array.prototype.slice.call(divList);
 // 对于函数中的arguments转换成数组的不会出现浏览器兼容问题
function toAry(){
    Array.prototype.slice.call(arguments);
    return arguments;
}

捕获异常

try{
    console.log(num);
}catch(e){// 形参e必须写,并且一般都写为e
    console.log("It's broken!");
}
console.log("ok!");
try{
    
}catch(e){
    console.log(e.message);
}finally{
    // 无论try中代码是否报错,finally中的代码都会执行
}
  • 实现浏览器兼容情况下的类数组转换成数组
 // 为防止全局作用域下相同属性名属性值冲突使用单例模式
var utils = {
    listToArray:function(likeAry){
        var ary = [];
        try {
            ary = Array.slice.call(likeAry);
        }catch(e){
            for(var i = 0; i<likeAry.length; i++){
                ary[ary.length] = likeAry[i];
            }
        }
        return ary;
    }	
}  
posted @ 2022-02-09 15:49  震惊IT行业  阅读(37)  评论(0)    收藏  举报