Javascript数组非空数组,长度为0

问题描述:

我使用基石js创建一个带搜索功能的列表。Javascript数组非空数组,长度为0

结果中的console.log的:

enter image description here

正如你可以看到阵列理应有它5个对象,但随后原为0。我不明白是什么可能是错误的。

var iniList = [ 
    new Spot("Park"), 
    new Spot("High School"), 
    new Spot("Soccer Stadium"), 
    new Spot("Railway Station"), 
    new Spot("Hospital") 
]; 


var viewModel = { 
    spots: ko.observableArray(iniList), 
    filter: ko.observable(''), 
    search: function(value) { 
     console.log(iniList); 

     viewModel.spots.removeAll(); 
     for (x = 0; x < iniList.length; x++) { 
      console.log("iniList[x]"); 
      if (iniList[x].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) { 
       viewModel.spots.push(iniList[x]); 
      } 
     } 
    } 
}; 
+2

另请参见http://knockoutjs.com/documentation/observableArrays.html:“所有这些函数相当于在底层数组**上运行本机JavaScript数组函数**,然后通知侦听器有关更改” – Ryan

+0

@squint是的,因为它从来没有进入for循环,我试图理解为什么 – MMrj

您正在运行“viewModel.spots.removeAll();”这删除了可观察数组的所有元素。