Фильтровать проблемы JS - PullRequest
0 голосов
/ 20 июня 2019

Я хочу отфильтровать на входе, а затем показать другой результат. Но, как вы можете видеть в выводе console.log, он меняет мой массив this.data.stationInfo.stations. Фильтр должен создать новый массив, а не изменять мой массив, это то, что я прочитал из документов mozilla Я думаю, что проблема с использованием 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: «длина копии» 4

JS: 'после copy.length this.data.stationInfo.stations.length' 4

JS: 'this.data.stationInfo.stations.length' 4

JS: 'copy.length' 0

JS: 'после copy.length this.data.stationInfo.stations.length' 0

JS: 'this.data.stationInfo.stations.length' 0

JS: 'copy.length' 0

JS: 'после copy.length this.data.stationInfo.stations.length' 0

JS: 'this.data.stationInfo.stations.length' 0

JS: «длина копии» 0

JS: 'после copy.length this.data.stationInfo.stations.length' 0

UPDATE:

NativeScript PlayGround: https://play.nativescript.org/?template=play-vue&id=1SXSNW

1 Ответ

1 голос
/ 20 июня 2019

Вы не должны создавать ссылки. На самом деле вы устанавливаете ссылку на ваш исходный массив, и тогда все мутации против вашей копии будут отражены в исходном массиве.

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