我需要創建一個函式來接收具有boolean屬性的物件,將其值更改為false,然后獲取陣列中的下一項并將其值更改為true。如果提供的物件是陣列中的最后一項,那么我們回到第一項。
換句話說,函式在被呼叫時應該有這些結果:
示例 1
const arr = [
{
id: 1,
chosen: false
},
{
id: 2,
chosen: true
},
{
id: 3,
chosen: false
},
];
const chosenObject = arr[1];
functionToBeCreated(chosenObject); // Outcome: [{ id: 1, chosen: false }, { id: 2, chosen: false }, { id: 3, chosen: true }]
示例 2
const arr = [
{
id: 1,
chosen: false
},
{
id: 2,
chosen: false
},
{
id: 3,
chosen: true
},
];
const chosenObject = arr[2];
functionToBeCreated(chosenObject); // Outcome: [{ id: 1, chosen: true }, { id: 2, chosen: false }, { id: 3, chosen: false }]
您對如何存檔有任何想法嗎?
uj5u.com熱心網友回復:
請參閱考慮代碼的解釋。
const arr = [
{
id: 1,
chosen: false
},
{
id: 2,
chosen: true
},
{
id: 3,
chosen: false
},
];
// This is your chosen pointer. It has to change, so it is not a constant
let chosenObject = 1;
function functionToBeCreated(chosen){
// Set the currently chosen property to false
arr[chosen].chosen = false
// Determine the next object.
// This is the remainder of the division by the length of the array
// this is a zero-based index.
let next = (chosen 1) % arr.length
// Set the "next" chosen property to true
arr[next].chosen = true
// Update your pointer
chosenObject = next
};
// 1st call
functionToBeCreated(chosenObject)
console.log(arr)
// 2nd call
functionToBeCreated(chosenObject)
console.log(arr)
// 3rd call
functionToBeCreated(chosenObject)
console.log(arr)
// 4th call
functionToBeCreated(chosenObject)
console.log(arr)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/421505.html
標籤:
下一篇:TypeScript問題物件陣列
