請在此代碼中幫助我 我是 UI 設計師并且不知道代碼 我有 Json 檔案有資料 從 id 1 到 id 25,我使用 id 和 math.random() 加載此資料代碼作業但我的問題相同id 顯示兩次或兩次以上我只需要顯示 25 個唯一的 id 例如結果是 (2, 4, 18, 14, 7, 13, 13, 4) 但我不希望相同的 id 顯示不止一個當 25 個 ID 顯示它們全部停止時
json檔案的后端代碼
const express = require('express');
const app = express();
const importData = require("./data.json");
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/posts', (req, res) => {
res.send(importData);
});
app.get('/posts/:id', (req, res) => {
const post = importData.find(c => c.id === parseInt(req.params.id));
if (!post) res.status(404).send("Error");
res.send(post);
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
app.listen(port, () => {
console.log(`Example app listening at ${port}`);
});
前端js檔案
const container = document.getElementById('container'); const loading = document.querySelector('.loading');
// this load 4 posts
getPost();
getPost();
getPost();
getPost();
window.addEventListener('scroll', () => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;
console.log( { scrollTop, scrollHeight, clientHeight });
if(clientHeight scrollTop >= scrollHeight - 5) {
// show the loading animation
showLoading();
}
});
function showLoading() {
loading.classList.add('show');
// load more data
setTimeout(getPost, 300)
}
async function getPost() {
// the orginal url have (25) id in the json file
// tips this is fake url i can't post the orginal url because it will my server
const postResponse = await fetch(`https://example.com/posts/${getRandomNr()}`);
const postData = await postResponse.json();
const data = { post: postData};
addDataToDOM(data);
console.log(data);
}
function getRandomNr() {
return Math.floor(Math.random() * 25) 1;
}
function addDataToDOM(data) {
const postElement = document.createElement('div');
postElement.classList.add('blog-post');
postElement.innerHTML = `
<h2 >${data.post.title}</h2>
<p >${data.post.body}</p>
<div >
<img src="${data.post.src}" alt="從 Json 檔案加載資料" />
<span>${data.post.title}</span>
</div>
`;
container.appendChild(postElement);
loading.classList.remove('show');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<h1>Blog Posts</h1>
<!-- <div >
<h2 >Blog post title</h2>
<p >Lorem ipsum dolor, sit amet consectetur adipisicing elit. Provident quod debitis in repellat veritatis minus ab ex maiores itaque quis.</p>
<div >
<img src="https://randomuser.me/api/portraits/women/26.jpg" alt="從 Json 檔案加載資料" />
<span>Leah Taylor</span>
</div>
</div> -->
</div>
<div >
<div ></div>
<div ></div>
<div ></div>
</div>
<script src="script.js"></script>
</body>
</html>
uj5u.com熱心網友回復:
您可以使用函式和陣列來處理不重復的相同數字,如下所示。您可以將數字陣列放在實作的頂部。
這不是明智的做法。你是說你是 UI 設計師。所以,我采用了可以理解的方式而不是更聰明的方式。
var numbers = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 20, 21, 22,
23, 24, 25,
];
function getRandomNr() {
var x = Math.floor(Math.random() * numbers.length);
const temp = numbers[x];
// find index of random value in numbers
// and delete it to not repeat number again
var index = numbers.indexOf(temp);
if (index > -1) {
numbers.splice(index, 1);
return temp;
} else {
// if code goes here that means
// we got all 25 numbers between 1 and 25
// and the numbers array is empty
// so we can return -1 or anything we want
return -1;
}
}
uj5u.com熱心網友回復:
嘗試這樣的事情var array = Object.values(myobject)會將所有物件自己的可列舉屬性值保存在一個陣列中。然后你想對陣列進行洗牌。你可以用這段代碼做到這一點。
var shuffledArray = array.sort((a, b) => 0.5 - Math.random());
最后,您將擁有一個包含隨機順序的物件所有值的陣列。
uj5u.com熱心網友回復:
您的問題的解決方案確實是通過創建一個專案串列然后進行迭代。
除了提到的方法之外,另一種方法是生成四個不同的數字,然后使用您的代碼實際對它們做一些有用的事情。
function showLoading() {
loading.classList.add('show');
const rnd = new Set();
do {
rnd.add(getRandomNr());
} while (rnd.size < 4);
// load more data
setTimeout(()=>rnd.forEach(nr => getPost(nr), 300));
}
async function getPost(id) {
const postResponse = await fetch(`https://example.com/posts/${id}`);
......
}
只是為了澄清:集合是一個專案串列,其中每個專案只能存在一次。因此,如果在您的情況下已經有一個已添加的數字,則不會再次添加,從而為您留下不同的專案。
完整代碼應如下所示:
const container = document.getElementById('container');
const loading = document.querySelector('.loading');
window.addEventListener('scroll', () => {
const {
scrollTop,
scrollHeight,
clientHeight
} = document.documentElement;
console.log({
scrollTop,
scrollHeight,
clientHeight
});
if (clientHeight scrollTop >= scrollHeight - 5) {
showLoading();
// show the loading animation
}
});
function showLoading() {
loading.classList.add('show');
const rnd = new Set();
do {
rnd.add(getRandomNr());
console.log(88)
} while (rnd.size < 4);
// load more data
console.log(rnd)
setTimeout(() => rnd.forEach(nr => getPost(nr), 300));
}
async function getPost(id) {
const postResponse = await fetch(`https://example.com/posts/${id}`);
const postData = await postResponse.json();
const data = {
post: postData
};
addDataToDOM(data);
}
function getRandomNr() {
return Math.floor(Math.random() * 25) 1;
}
function addDataToDOM(data) {
const postElement = document.createElement('div');
postElement.classList.add('blog-post');
postElement.innerHTML = `
<h2 >${data.post.title}</h2>
<p >${data.post.body}</p>
<div >
<img src="${data.post.src}" alt="從 Json 檔案加載資料" />
<span>${data.post.title}</span>
</div>
`;
container.appendChild(postElement);
loading.classList.remove('show');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" id="container">
<h1>Blog Posts</h1>
<!-- <div >
<h2 >Blog post title</h2>
<p >Lorem ipsum dolor, sit amet consectetur adipisicing elit. Provident quod debitis in repellat veritatis minus ab ex maiores itaque quis.</p>
<div >
<img src="https://randomuser.me/api/portraits/women/26.jpg" alt="從 Json 檔案加載資料" />
<span>Leah Taylor</span>
</div>
</div> -->
</div>
<div class="loading">
<div class="ball"></div>
<div class="ball"></div>
<div class="ball"></div>
</div>
<script src="script.js"></script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373525.html
標籤:javascript json 接口
