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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3865139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:25:04  来源:igfitidea点击:

Cast javascript object to array. How to?

javascriptjquery

提问by Jhonny D. Cano -Leftware-

I have made this sandbox test:

我做了这个沙箱测试:

<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>

I realize I can use jQuery's function $.map for making that line of code work, but, what am I missing on javascript datatypes?

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

采纳答案by Mike Morearty

I'm pretty sure this isn't a type problem, it's because IE didn't have the Array.map()function until IE 9. See http://msdn.microsoft.com/en-us/library/k4h76zbx(v=VS.85).aspxfor a list of supported functions. See http://msdn.microsoft.com/en-us/library/ff679976(v=VS.94).aspxfor a description of the Array.map()function in IE 9.

我很确定这不是类型问题,这是因为 IEArray.map()直到 IE 9 才具有该功能。请参阅http://msdn.microsoft.com/en-us/library/k4h76zbx(v=VS.85 ).aspx获取支持的函数列表。请参阅http://msdn.microsoft.com/en-us/library/ff679976(v=VS.94).aspx了解Array.map()IE 9中的功能描述。

回答by Sean McMillan

If you have an array-like object, (like arguments, for example,) you can get a real array made from it by calling Array.prototype.slice.call(o).

如果您有一个类似数组的对象(arguments例如 ),您可以通过调用Array.prototype.slice.call(o).

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

awill be ["a", "b"]. This will only work right if you have a correctly set lengthproperty.

a["a", "b"]。这只有在您拥有正确设置的length属性时才能正常工作。

回答by Matthew Baker

I think you are trying too hard...

我觉得你太努力了...

It's easiest with jQuery (or similar library)

使用 jQuery(或类似库)最简单

For this object:

对于这个对象:

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

Arrays have a fixed key system so for the object above, you've got to throw away either the keys (a, b, c) or the values (1, 2, 3)

数组有一个固定的键系统,所以对于上面的对象,你必须扔掉键 (a, b, c) 或值 (1, 2, 3)

So either this:

所以要么这样:

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

or this:

或这个:

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

回答by Adaddinsane

A year ago now, but I may as well mention jQuery's makeArray function http://api.jquery.com/jQuery.makeArray/

一年前的现在,但我不妨提一下 jQuery 的 makeArray 函数http://api.jquery.com/jQuery.makeArray/

回答by Peter Ajtai

Use a forloop for max browser compatibility.

使用for循环以获得最大的浏览器兼容性。

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

在 Javascript 中,所有数组都是对象,但并非所有对象都是数组。看看这个 Perfection Kills 页面,它描述了如何检查某个东西是否是一个数组。

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):

要检查数组,您可以使用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

jsFiddle 示例

回答by drewww

Among many other small utilities for manipulating objects and arrays, Underscore.js offers a toArray(obj)helper method. Documentation here: http://underscorejs.org/#toArray

在许多其他用于操作对象和数组的小实用程序中,Underscore.js 提供了一个toArray(obj)辅助方法。文档在这里:http: //underscorejs.org/#toArray

It's not totally obvious from the way the documentation is written, but it works like a charm on arbitrary objects. When given an object, it iterates over the values and returns a list that contains just those values.

从文档的编写方式来看,这并不完全显而易见,但它就像是对任意对象的一种魅力。当给定一个对象时,它会遍历这些值并返回一个只包含这些值的列表。