前端基础学习

数组类型检测与转换

2020-03-16  本文已影响0人  小雪洁
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>类型检测与转换</title>
    </head>
    <body>
        <div>hxj</div>
        <div>ydc</div>
        
        <script>
            //类型检测
            const array=[1,2,3];
            console.log(Array.isArray(array));
            //数组转字符串
            /* console.log(array.toString());//1,2,3
            console.log(array.join("-"));//1-2-3
            console.log(String(array));//1,2,3
            const str=array.join("-");
            console.log(location.href+"?id="+str); */
            //字符串转数组
            const hxj="haoxuejie";
            console.log(hxj.split());//["haoxuejie"]
            console.log(hxj.split(""));// ["h", "a", "o", "x", "u", "e", "j", "i", "e"]
            const hy="hxj,ydc";
            console.log(hy.split(","));//["haoxuejie", "yangdingchuan"];
            //Array.from(str)可以将字符串转成数组,因为字符串有length
            console.log(Array.from(hy));//["h", "x", "j", ",", "y", "d", "c"]
            const obj={
                name:"hhh",
                age:"30"
            };
            console.log(Array.from(obj));//[]
            const o={
                0:"hhh",
                1:"30",
                length:2
            }
            console.log(Array.from(o));//["hhh", "30"]
            let divs=document.querySelectorAll("div");
            console.log(divs);//NodeList(2) [div, div]
            //Array.from()可以转换成数组,还可以对数组元素进行一定的处理
            console.log(Array.from(divs));// [div, div]
            Array.from(divs,function(item){
                console.log(item.innerHTML);
                item.style.background="pink";
                return item;
            });//hxj   ydc
        </script>
    </body>
</html>

上一篇下一篇

猜你喜欢

热点阅读