Javascript 在这种情况下,为什么“push”方法对对象有效?
我的印象是push方法适用于数组,而不是对象。。。但是为什么下面的代码段可以工作呢Javascript 在这种情况下,为什么“push”方法对对象有效?,javascript,arrays,object,ecmascript-6,Javascript,Arrays,Object,Ecmascript 6,我的印象是push方法适用于数组,而不是对象。。。但是为什么下面的代码段可以工作呢 this.usersByMovie = {}; profiles.forEach(profile => { const movieID = profile.favoriteMovieID; if (this.usersByMovie[movieID]) { // the object property is just being accessed using the square br
this.usersByMovie = {};
profiles.forEach(profile => {
const movieID = profile.favoriteMovieID;
if (this.usersByMovie[movieID]) {
// the object property is just being accessed using the square brackets
// so `this.usersByMovie` is still an object, not an array
// but why is the `push` method working on this object?
this.usersByMovie[movieID].push(profile.userID);
}
else {
this.usersByMovie[movieID] = [profile.userID];
}
});
this.usersByMovie[id]实际上是一个数组,而this.usersByMovie是一个对象
this.usersByMovie[movieID] = [profile.userID];
这行代码将This.usersByMovie[id]作为一个数组。This.usersByMovie[id]实际上是一个数组,而This.usersByMovie是一个对象
this.usersByMovie[movieID] = [profile.userID];
这行代码将.usersByMovie[id]作为一个数组。您正在将.usersByMovie[movieID]作为一个数组,而不是这个数组。usersByMovieusersByMovie是一个类型为{movieId1:[]的对象。因此,usersByMovie只是作为一个对象创建的,没有任何数组。但是,我假设数组是在推送第一个元素时创建的。正确吗?@感恩.push不会创建数组,数组的创建是在您的else中完成的:this.usersByMovie[movieID]=[profile.userID]。push只将一个元素附加到现有的数组中。usersByMovie[movieID]是一个数组,而不是这个数组。usersByMovieusersByMovie是一个类型为{movieId1:[]的对象。因此,usersByMovie只是作为一个对象创建的,没有任何数组。但是,我假设数组是在推送第一个元素时创建的。正确吗?@感恩.push不会创建数组,数组的创建是在您的else中完成的:this.usersByMovie[movieID]=[profile.userID]。push仅将元素附加到现有数组没有数组,但当您第一次按下时,这意味着数组已在else中创建。因此,从数组的第二个元素调用push。没有数组,但是当您第一次push时,这意味着数组已经在else中创建。因此,从数组的第二个元素调用push。