我只是想將一個 JSON 物件存盤到一個全域變數中,這樣我就不需要在每次更新搜索引數時都運行 fetch(我們正在構建一個房地產串列界面)。下面是我的代碼,我確定我誤解了異步/等待語法的一些基本內容,因為在元素單擊時觸發的函式(filterListings)正在檢索一個空陣列。
let allListings = [];
let filteredListings = [];
async function getListings() {
if(allListings.length == 0){
let response = await fetch(URL);
allListings = await response.json();
}
filteredListings = allListings;
}
/*Filtering function on search button click*/
function filterListings(){
filteredListings.length = 0;
console.log(allListings.length); //allListings is 0???
for(let i = 0; i < allListings.length; i ){
console.log("filtering happening");
}
numOfListings = filteredListings.length;
printListings();
}
/*Iterating through filteredListings to get only necessary listings to print on the page*/
function printListings(){
let listingsWrapper = document.getElementById("listings_wrapper");
let currentPageLimit = ((currentPage !== totalPages) ? listingPageLimit*currentPage : filteredListings.length);
document.getElementById("number_of_listings").innerHTML = numOfListings;
console.log("These are listings " listingOffset " - " currentPageLimit)
for (let i = listingOffset; i < currentPageLimit; i ) {
listingsWrapper.innerHTML = `<a class='listing_container' href='/listings?address=${styleLink(filteredListings[i].StreetNumber, filteredListings[i].StreetName, filteredListings[i].StreetSuffix, filteredListings[i].City, filteredListings[i].PostalCode, filteredListings[i].MLSNumber)}' style='background-image:url("https://bm-re-listings.s3.us-west-2.amazonaws.com/test_folder/pic-${filteredListings[i].Matrix_Unique_ID}-0.jpg")'>
<div class='listing_details'>
<div class='listing_details_main'>
<h2 class='listing_title'>${styleTitle(filteredListings[i].StreetNumber, filteredListings[i].StreetName, titleCase(filteredListings[i].StreetSuffix), filteredListings[i].City)}</h2>
<p class='listing_subtitle'>${filteredListings[i].City}, ${filteredListings[i].PostalCode}</p>
<p class='listing_stats'>${styleRoomNum(filteredListings[i].BedsTotal)}${styleRoomNum(filteredListings[i].BathsTotal)}${filteredListings[i].SqFtTotal} sqft</p>
</div>
<div class='listing_details_aside'>
<h3 class='listing_price'>${stylePrice(filteredListings[i].ListPrice)}</h3>
<div class='listing_cta'><span>Details</span></div>
</div>
</div>
</a>`
}
/*Hide load more button if no more listings*/
if(currentPage == totalPages){
document.getElementById("load_more").style.display = "none";
} else {
document.getElementById("load_more").style.display = "block";
}
}
/*Attaching event listner to the search button*/
document.getElementById("search_button").addEventListener("click", function(){
currentPage = 1;
listingOffset = (currentPage -1) * listingPageLimit
filterParams.lowPrice = (document.getElementById("price_min").value <= document.getElementById("price_min").getAttribute("min") ? 0 : document.getElementById("price_min").value);
filterParams.highPrice = (document.getElementById("price_max").value >= document.getElementById("price_max").getAttribute("max") ? 1000000000 : document.getElementById("price_max").value);
filterParams.lowSqft = (document.getElementById("sqft_min").value <= document.getElementById("sqft_min").getAttribute("min") ? 0 : document.getElementById("sqft_min").value);
filterParams.highSqft = (document.getElementById("sqft_max").value >= document.getElementById("sqft_max").getAttribute("max") ? 100000 : document.getElementById("sqft_max").value);
filterParams.address = document.getElementById("address_search").value;
filterListings();
});
/*Final Function Firing Order*/
async function refreshListing(){
await getListings();
await printListings();
}
refreshListing();
我發現的問題是,當單擊 ID 為“search_button”的元素并觸發 filterListings 函式時,它會將 allListings 作為空陣列回傳,因此 for 回圈甚至不會觸發。
任何幫助深表感謝!
uj5u.com熱心網友回復:
問題在于 的參考filteredListing與 相同allListings。它們是相同的潛在價值
filteredListings = allListings;
在這個簡單的例子中可以觀察到這種行為
let allListings;
let filteredListings;
allListings = ['a', 'b', 'c'];
filteredListings = allListings;
console.log(allListings); // ['a', 'b', 'c']
filteredListings.length = 0;
console.log(allListings); // []
這個問題在網路上的許多地方都有概述,例如這里JavaScript 是否通過參考傳遞?
要修復,只需復制底層物件,而不是使用相同的物件。對于我們的簡單示例:
let allListings;
let filteredListings;
allListings = ['a', 'b', 'c'];
filteredListings = [...allListings]; // copy the array
console.log(allListings); // ['a', 'b', 'c']
filteredListings.length = 0;
console.log(allListings); // ['a', 'b', 'c']
對于您的代碼,您的函式應為:
async function getListings() {
if(allListings.length == 0){
let response = await fetch(URL);
allListings = await response.json();
}
filteredListings = [...allListings]; // clone all listings into filtered
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/443538.html
標籤:javascript json 异步 异步等待
