简体   繁体   English

从JavaScript对象返回多个变量的正确方法

[英]Proper way to return multiple variable from a javascript object

I'm currently learning more about the inner workings of javascript objects and came across an example where multiple variables were returned from the object: 我目前正在学习有关javascript对象内部工作的更多信息,并遇到了一个从该对象返回多个变量的示例:

var squareGrid = function(width, n, z) {
        width = width || 1;
        n = n || 4;
        var z = z || width / 2.0;

        var edges = [],
            pts = [];

        var step = width / n;
        for (var u = 0; u < n; u++) {
            var u_added = u * n * 4;
            for (var v = 0; v < n; v++) {
                var delta = u_added + 4 * v;

                var t_v = step * (v - n / 2);
                var t_u = step * (u - n / 2);

                pts.push([t_v, t_u, z]); // top left
                pts.push([t_v, t_u + step, z]); // top right
                pts.push([t_v + step, t_u + step, z]); // bottom right
                pts.push([t_v + step, t_u, z]); // bottom left

                edges.push([delta + 0, delta + 1]);
                edges.push([delta + 1, delta + 2]);
                edges.push([delta + 2, delta + 3]);
                edges.push([delta + 3, delta + 0]);
            }

        }
        return {
            edges: edges,
            pts: pts
        };
    }

In this case, in order to return both edges and points , it looks like there are key-value pairs being returned where the keys and values are the same thing. 在这种情况下,为了同时返回edgespoints ,似乎要返回键-值对,其中键和值是相同的。 Is this method necessary or can the following just be done? 此方法是否必要?是否可以执行以下操作?

return{ edges, pts}};

You would be returning an object where the keys would be edges and the values would be the return value of edges. 您将返回一个对象,其中键将是edge,值将是edge的返回值。

x = squareGrid(400, 2, 5)

x.edges
// edges
x.pts
//pts

You could do something like: data = callfunction() -> return [edges, points] 您可以执行以下操作:data = callfunction()-> return [edges,points]

data[0]
// edges
data[1]
//points

** Correction ** when keys are stored in a js hash it serializes the key before attempting to store the value **更正**当密钥存储在js哈希中时,它将在尝试存储值之前对密钥进行序列化

what would get stored is the serialized version of the array as the key, with the value being the array 将存储的是数组的序列化版本作为键,值是数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM