Javascript 数组作为类javascript中的数据成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26820262/
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-22 23:24:55  来源:igfitidea点击:

array as data member in a class javascript

javascriptjqueryobject-oriented-analysis

提问by user3316523

I am new one in object oriented javascript and trying to define a class, that have an array as a data member. this data member of class storing objects of an other class as an array.

我是面向对象的 javascript 中的新手,并试图定义一个类,该类将数组作为数据成员。这个类的数据成员将另一个类的对象存储为数组。

it will be more clear by this example

这个例子会更清楚

function classA(id, objB_01)
{

    this.id = id;   // data member that store a simple value
    this.arrayname = objB_01  // How multiple instance of classB is stored in this array 


}

function classB( id, name, status)
{
     this.id = id;
     this.name = name;
     this.status = status 
}

objB_01 = new classB("01", "john", "single");
objB_02 = new classB("02", "smith" "single");
objB_03 = new classB("03", "nina", "married");

now my question is how i can write classAso that single instance of classAhold an array that store mutiple object of classB

现在我的问题是我如何编写classA这样的单个实例来classA保存一个存储多个对象的数组classB

Something like this

像这样的东西

objA = new classA("01",objB_01);
objA.arrayname = objB_02;
objA.arrayname = objB_03;

Now Finally objAcontain one string and one array that store multiple objects of classB

现在最终objA包含一个字符串和一个数组,用于存储 classB 的多个对象

Please point me in the right direction

请指出我正确的方向

回答by meir shapiro

One option can be to initialize an empty array in the constructor function and also have some method to add objects to the array.

一种选择是在构造函数中初始化一个空数组,并且还有一些方法可以将对象添加到数组中。

function classA (id) {
    this.id = id;
    this.array = [];

    this.add = function (newObject) {
        this.array.push(newObject);
    };
}

Then you can do this:

然后你可以这样做:

objA = new classA("01");
objA.add(objB_01);
objA.add(objB_02);
objA.add(objB_03);

回答by Michael Angstadt

It might do some good to just dig into the spec docs around JavaScript Arrays.

深入研究JavaScript Arrays的规范文档可能会有所帮助。

Beyond that, to answer your question about having a classA wherein a single instance has an array of multiple classB instances - I believe you're looking for the array method .push()

除此之外,要回答有关拥有 classA 的问题,其中单个实例具有多个 classB 实例的数组 - 我相信您正在寻找数组方法 .push()

As well, you'll probably want to beef up your class definition, utilizing a standard overloaded constructor pattern for JavaScript.

同样,您可能希望加强类定义,使用 JavaScript 的标准重载构造函数模式。

Something like this

像这样的东西

function classA(id, objarray)
{

    this.id = id;   // data member that store a simple value
    this.arrayname = objarray || []; //if objarray isn't passed it'll initiate an empty array 
}
function classB( id, name, status)
{
     this.id = id;
     this.name = name;
     this.status = status 
}

objB_01 = new classB("01", "john", "single");
objB_02 = new classB("02", "smith" "single");
objB_03 = new classB("03", "nina", "married");

var objBarray = [objB_01, objB_02, objB_03];

//now you can use construct & initiate classA in two different ways
//Push each object individually
var objA = new classA("01");
objA.arrayname.push(objB_01);
objA.arrayname.push(objB_02);
objA.arrayname.push(objB_03);

//or push the entire list at once
var objA = new classA("01", objBarray);

回答by guest271314

Try

尝试

        var data = {};

        var classData = function (id, name, status, options) {
            if (options) {
                this.id = options.id;
                this[options.arrayname] = [];
            };
            if (!this.hasOwnProperty("id")) {
                throw new Error("No id set on `classData` array."
                + "Please set `id` for `classData` at `options` object")
            };
            var j = (id && name && status) ? JSON.stringify({
                id: id,
                name: name,
                status: status
            }) : false;
            j ? this[Object.keys(this).filter(function (v) {
                return v !== "id"
            })[0]].push(JSON.parse(j)) : null;
            return this
        }.bind(data);
        // set `id` at `data` , 
        // add first item to `data.arrayname` 
        classData("01", "abc", "single", {"id":"01", "arrayname":"files"});
        // set data at `data`
        classData("02", "def", "married");
        classData("02", "ghi", "single");
        // read `classData`
        console.log(classData());

        var data = {};
        
        var classData = function (id, name, status, options) {
            if (options) {
                this.id = options.id;
                this[options.arrayname] = [];
            };
            if (!this.hasOwnProperty("id")) {
                throw new Error("No id set on `classData` array."
                + "Please set `id` for `classData` at `options` object")
            };
            var j = (id && name && status) ? JSON.stringify({
                id: id,
                name: name,
                status: status
            }) : false;
            j ? this[Object.keys(this).filter(function (v) {
                return v !== "id"
            })[0]].push(JSON.parse(j)) : null;
            return this
        }.bind(data);
        // set `id` at `data` , 
        // add first item to `data.arrayname` 
        classData("01", "abc", "single", {"id":"01", "arrayname":"files"});
        // set data at `data`
        classData("02", "def", "married");
        classData("02", "ghi", "single");
        // read `classData`
        console.log(classData());