// Returns the first selected record.
extjs RowSelectionModel getSelected

文档中说明了,此方法返回的是第一条选中的记录。如果没有选中记录,而调用此方法,会返回什么值呢?


测试一下就知道是undefined,查看源码,找原因。

首先是,getSelected()方法的定义:

getSelected : function(){
    return this.selections.itemAt(0);
}


然后是,selections的定义:

this.selections = new Ext.util.MixedCollection(false, function(o){
    return o.id;
});


MixedCollection中itemAt()方法:

itemAt : function(index){
    return this.items[index];
},


也就是getSelected()方法,相当于取array的首元素,等价于下面方法:

var records = [];
alert(records[0]); // undefined



所以,判断用户是否选择了条目的正确判断方法为:

if(typeof(selection.getSelected()) !== 'undefined'){ // 选择了记录
    // doSomething
}


有关undefined和null的区别,以及判断,这里不赘述!