我想过滤输入,然后显示不同的结果。
但就像您在 console.log 输出中看到的那样,它更改了我的 this.data.stationInfo.stations 数组。
过滤器应该创建一个新数组,而不是更改我从 mozilla docs 中读取的数组。 。我认为问题在于 this
的使用?有人知道如何解决吗?
onTextChanged: function () {
let copy = this.data.stationInfo.stations;
console.log("this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
copy = copy
.filter(el => {
return el.eng站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
||
el.站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
||
el.traWebsiteCode.startsWith(this.data.searchBar.search.toLowerCase())
});
this.data.resultDetails.stations = copy;
console.log("copy.length", copy.length);
console.log("after copy.length this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
},
console.log输出:
JS: 'this.data.stationInfo.stations.length' 239
JS: 'copy.length' 4
JS: 'after copy.length this.data.stationInfo.stations.length' 4
JS: 'this.data.stationInfo.stations.length' 4
JS: 'copy.length' 0
JS: 'after copy.length this.data.stationInfo.stations.length' 0
JS: 'this.data.stationInfo.stations.length' 0
JS: 'copy.length' 0
JS: 'after copy.length this.data.stationInfo.stations.length' 0
JS: 'this.data.stationInfo.stations.length' 0
JS: 'copy.length' 0
JS: 'after copy.length this.data.stationInfo.stations.length' 0
更新:
NativeScript PlayGround:https://play.nativescript.org/?template=play-vue&id=1SXSNW
最佳答案
您不应该创建引用。实际上,您设置了对原始数组的引用,然后针对您副本的所有突变都将反射(reflect)在原始数组上。
onTextChanged: function () {
console.log("this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
let newArray = this.data.stationInfo.stations
.filter(el => {
return el.eng站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
||
el.站名.toLowerCase().startsWith(this.data.searchBar.search.toLowerCase())
||
el.traWebsiteCode.startsWith(this.data.searchBar.search.toLowerCase())
});
this.data.resultDetails.stations = newArray;
console.log("copy.length", copy.length);
console.log("after copy.length this.data.stationInfo.stations.length", this.data.stationInfo.stations.length);
}
此外,我建议您改进代码并在一个地方完成所有需要的事情。您可以迭代数组并直接排除所有需要的电台。这是一个例子:
onTextChanged: function () {
const stations = this.data.stationInfo.stations;
function doSearch(el,str) {
return
el.eng站名.toLowerCase().startsWith(str) ||
el.站名.toLowerCase().startsWith(str) ||
el.traWebsiteCode.startsWith(str);
}
for(let j=0; j < stations.length; j++){
if(!doSearch(stations[j], this.data.searchBar.search.toLowerCase())){
stations.splice(j, 1);
}
}
console.log(stations);
}
关于javascript - 过滤JS问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56688127/