从for循环到forEach,再到for...of,再到loda

2018-07-17  本文已影响0人  故林青衫

1.for循环与forEach,比较简单的操作就不贴代码了,唯一不同的在于for循环内部相应break等中断操作,forEach不支持,
2.for...of,基于es6的新方法,完美支持break等中断循环操作,

for (let item of CityDataJson) {
        if (nameId == item.id) {
            for (let cityList of item.city) {
                if (cityId == cityList.id) {
                    for (let areaList of cityList.area) {
                        if (areaId == areaList.id) {
                            this.setState({
                                provinceId: CityDataJson[preventIndex].id,
                                provinceDesc: CityDataJson[preventIndex].name,
                                cityId: cityList[cityIndex].id,
                                cityDesc: cityList[cityIndex].name,
                                areaId: areaList[areaIndex].id,
                                areaDesc: areaList[areaIndex].name
                            });
                            break;
                        }
                    }
                    break;
                }
            }
            break;
        }
    }

3.基于lodash的findIndex方法,快速找到对应数据下标,代码如下;

   let preventIndex = findIndex(CityDataJson, ['id', nameId]),
        cityList = CityDataJson[preventIndex].city,
        cityIndex = findIndex(cityList, ['id', cityId]),
        areaList = cityList[cityIndex].area,
        areaIndex = findIndex(areaList, ['id', areaId]);
    console.log(cityIndex, cityId);
    this.setState({
        provinceId: CityDataJson[preventIndex].id,
        provinceDesc: CityDataJson[preventIndex].name,
        cityId: cityList[cityIndex].id,
        cityDesc: cityList[cityIndex].name,
        areaId: areaList[areaIndex].id,
        areaDesc: areaList[areaIndex].name
    });
上一篇下一篇

猜你喜欢

热点阅读