views:

22

answers:

1

I've been coding javascript like this:

var Foo = {
    something: function() {

    },
    someValue: 0,
    someArray: [],
    someObject: {},
    anotherFunction: function (id) {
         this.someArray.push(id); // works - adds value to array someArray
    },
    removeSomething: function(id) {
         this.someArray.without(id); // doesn't work - value remains in array someArray
    }
};

If in one of these functions, I push a value onto someArray (defined as []), it appears in the array, but I can't remove it using Array.without(). On checking with typeof, I found that it is an object, even though it's obviously an array. Whether there is some fundamental understanding to which I'm not aware, I'll leave that up to you to decide.

I would really like to push and pop (without) elements off this array while it's being treated like an array. Why is this being treated like an object and not an array?

+2  A: 

Array#without() does not change your array, it returns a new array without the specified value(s). If you want to overwrite the array, try

removeSomething: function(id) {
     this.someArray = this.someArray.without(id);
}

Javascript doesn't identify arrays as being of type Array when using the typeof operator, but as an Object instead. If you want to determine if a variable is an array, there are other ways to do so (see this question, for example).

Daniel Vandersluis
Also, typeof returns object rather than array because Prototype will create an object out of your array so that you can call `.without()`
Michal
@Michal Prototype actually adds its methods into `Array.prototype`, so an array in Prototype is still a native array (or else `var arr = []` wouldn't be extended), just with added methods.
Daniel Vandersluis
Thanks for the quick reply. I just assumed that the Array functions extended the input data like the Element methods. It would be nice to have one that changes the array so the methods can be chained.
Mike
@Michal: That's not the reason. Even without prototype an array is typeof Object. The reason is because this is a historical mistake. When Netscape introduced javascript this was how it was. But that version of javascript was meant to be a rough implementation and they intended to fix bugs later. But Microsoft copied javascript into IE before they did and too many sites were already using that version of js, bugs and all, so fixing it would break compatibility.Yes, in js all are objects even arrays and strings. But it could have been implemented better like typeof string.
slebetman
@Mike `Element` is a Prototype-specific class that wraps a DOM element (probably at least partially because there isn't one cross-browser object to represent a DOM element). If you wanted, you could write your own method like `without` which updates the array, and then extend Array.prototype with it.
Daniel Vandersluis
Doh! I knew that.
Michal