javascript中的字符串和數組的互轉

javascript中的數組轉換成字符串用toString(),或者用join()。javascript

將數組和字符串用+鏈接,賦給一個變量,這個變量自動轉變成字符串了。html

 

字符串轉換成數組用split(',')java

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>js中數組和字符串的互轉</title>
</head>

<body>

    <script>

        var msgsnew = ["test", "test", "test", "test", "test"];
        //var tstr=msgsnew.join()        
        var tstr = msgsnew.join(',');    //數組轉字符串
        console.log("tstr", tstr);
        var tstrtwo = msgsnew.toString();       //數組轉字符串
        var tstrthree = "能夠轉字符串的" + msgsnew    //js中的+
        console.log("+後轉變成字符串的", tstrthree, typeof tstrthree);
        console.log("數組:" + msgsnew + ":" + (msgsnew instanceof Array), "數組轉字符串:" + tstrtwo + ":" + (tstrtwo instanceof Array));
        console.log(msgsnew);

        var tarra = tstr.split(',');    //字符串轉數組

        console.log(msgsnew instanceof Array, typeof tstr, tarra);
    </script>

</body>

</html>
相關文章
相關標籤/搜索