Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - Using function of an object after grabbing it from array

When I try to grab the object from the array, the type is undefined. Therefore I cannot use a method from the undefined object as it doesn't exist. I am relatively new to JavaScript and I have come straight from Java so the way of retrieving objects is kind of new to me. This is what I currently have.

var fleetAmount = 0;
var fleets = [];
function Fleet(number) {
    this.number = number;
    this.activities = [];
    this.addActivity = function (activity) {
        this.activities.push(activity);
    };
    fleets.push(this);
}
var getFleet = function(fleetNumber) {
    return fleets[fleetAmount - fleetNumber];
}

This is where I try to grab the object and preform the function

const Fl = require(‘fleet.js’);
const fleet = Fl.getFleet(fleetNumber);
fleet.addActivity(activity);

I am also working in Node.js, which is how I am using the require method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In combination with the answer from @audzzy I changed the getFleet() function so that it would be more efficient. I tested it out and it worked. This is what I used

    function getFleet(fleetNumber) {
        let result = fleets.filter(function (e) {
            return e.number = fleetNumber;
        })
        return result[0];
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...