代码之家  ›  专栏  ›  技术社区  ›  Jhonny D. Cano -Leftware-

将javascript对象强制转换为数组。如何?

  •  21
  • Jhonny D. Cano -Leftware-  · 技术社区  · 15 年前

    我做了这个沙盒测试:

    <html>
        <head>
            <title>whatever</title>
            <script type="text/javascript">
                function myLittleTest() {
                    var obj, arr, armap;
    
                    arr = [1, 2, 3, 5, 7, 11];
    
                    obj = {};
                    obj = arr;
                    alert (typeof arr);
                    alert (typeof obj);
    
                    // doesn't work in IE
                    armap = obj.map(function (x) { return x * x; });
                    alert (typeof armap);
    
                }
                myLittleTest();
            </script>
        </head>
        <body>
        </body>
    </html>
    

    我意识到我可以使用jquery的函数$.map使代码行正常工作,但是,我在javascript数据类型上缺少什么?

    6 回复  |  直到 12 年前
        2
  •  56
  •   Marek Sebera    13 年前

    arguments Array.prototype.slice.call(o)

    var o = {0:"a", 1:'b', length:2};
    var a = Array.prototype.slice.call(o);
    

    a ["a", "b"] length

        3
  •  24
  •   Taryn Frank Pearson    13 年前

    var obj = {a: 1, b: 2, c: 3};
    

    var arr = $.map(obj, function (value, key) { return value; });
    

    var arr = $.map(obj, function (value, key) { return key; });
    
        5
  •  5
  •   Peter Ajtai    15 年前

    for

    this Perfection Kills page

    Object.prototype.toString.call(theObject) [object Array] [object Object]

                function myLittleTest() 
                {
                    var obj, arr, armap, i;    
    
                      // arr is an object and an array
                    arr = [1, 2, 3, 5, 7, 11]; 
    
                    obj = {}; // obj is only an object... not an array
    
                    alert (Object.prototype.toString.call(obj));
                      // ^ Output: [object Object]
    
                    obj = arr; // obj is now an array and an object
    
                    alert (Object.prototype.toString.call(arr));
                    alert (Object.prototype.toString.call(obj));
                      // ^ Output for both: [object Array]
    
                    // works in IE
                    armap = [];
                    for(i = 0; i < obj.length; ++i)
                    {
                        armap.push(obj[i] * obj[i]);
                    }
    
                    alert (armap.join(", ")); 
    
                }
                // Changed from prueba();
                myLittleTest();
    

    jsFiddle example

        6
  •  2
  •   drewww    12 年前