开发者

Prototype: Array is an Object and not array?

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?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜