1. 程式人生 > >javascript中的物件轉陣列的方法

javascript中的物件轉陣列的方法

1. 物件沒有length屬性 2.Array.prototype.slice.call(obj)能將具有length屬性的物件轉成陣列,不帶length屬性的物件,只能宣告陣列去轉換
<!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>Document</title>
</head>
<body>
    <script>
              // 1. 物件沒有length屬性
             //     Array.prototype.slice.call(obj)能將具有length屬性的物件轉成陣列,不帶length屬性的物件,只能宣告陣列去轉換
    let obj = {0: 'a', 1: 'b', 2:'c',length:3};
    let obj1 = {0: 'a', 1: 'b', 2:'c'};
    let arr = Array.from(obj); // ['a','b','c'];
    var arr2=[];
   for(var i in obj){
        arr2.push(obj[i]);
   }
  var arr3= Array.prototype.slice.call(obj)
    console.log(arr,arr2,arr3);


    //會輸出undefined,因為物件是沒有length屬性的。
   // console.log(obj1.length);
    


     function test(a, b, c, d) {
            var arg = Array.prototype.slice.call(arguments, 1);
            alert(arg);
        }
        test("a", "b", "c", "d"); //b,c,d

//通用的轉化陣列的方法
        var toArray = function (s) {
            if (s.length) {
                return Array.prototype.slice.call(s);
            }
            else {
                var arr = [];
                for (var i in s) {
                   arr[i] = s[i];
                    //or
                   // arr.push(s[i]);
                }
                return arr;
            }

        }
    console.log(toArray(obj1));


    var t={
         id:2,
         name:"zain",
         sex:'男'
    };
    console.log(toArray(t));
    console.log(t['name'],t.name);





    </script>


</body>
</html>