0

The following code loops over an array. It is running within a casperJS script and therefore a phantomJS headless browser environment

socket.on('list', function(data){
                console.log("Message", JSON.stringify(data)); //no func def in this data
                var localMatchStore= [];
                for (var i in data.matches) {
                   localMatchStore.push(data.matches[i]);
                }
                console.log(localMatchStore);

            });

This returns the data I expect but also a function definition as the last item in the array. Why is this?

0580:MS101:2014,0580:MS127:2014,0580:MS128:2014,0901:LS162:2014,function () {
        for(var i=0,sum=0;i<this.length;sum+=this[i++]);
        return sum;
    }

1 Answer 1

1

Try using hasOwnProperty() with your for..in. That loop construct can include members of the object that are inherited through the prototype chain. hasOwnProperty() ensures that the property is a direct member.

socket.on('list', function(data){
    console.log("Message", JSON.stringify(data)); //no func def in this data

    var localMatchStore= [];

    for (var i in data.matches) {
        if (data.matches.hasOwnProperty(i)) localMatchStore.push(data.matches[i]);
    }

    console.log(localMatchStore);

});

For a more in-depth discussion of this function see here on MDN.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.