Cast javascript object to array. How to?

前端 未结 6 1614
有刺的猬
有刺的猬 2020-12-08 20:47

I have made this sandbox test:


    
        whatever
        

        
6条回答
  •  天命终不由人
    2020-12-08 21:24

    Use a for loop for max browser compatibility.

    In Javascript all arrays are objects, but not all object are arrays. Take a look at this Perfection Kills page which describes how to check that something is an Array.

    To check for an array, you can use Object.prototype.toString.call(theObject). This will return [object Array] for an object that is an Array and [object Object] for an object that's not an Array (see example below):

                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

提交回复
热议问题