我從 API 取回資料——只是一個與每個鍵相關的數值物件——然后構建一個簡單的句子來為用戶顯示資料。但是,我只想包含大于 0 的資料值。這是一個模擬資料的示例:
let data = {red: 100, blue: 200, yellow: 0, green: 400};
let resultsSentence = `We found ${data.red} red posts, ${data.blue} blue posts, and ${data.green} green posts.`
console.log(resultsSentence)
如您所見,我在結果陳述句中省略了黃色,因為它的值為0。當然,我需要能夠根據回傳的任何資料動態生成這句話。如果我使用條件陳述句,那將是一團糟,因為可能的場景太多(撰寫 15 個 if/else 陳述句似乎不是一個好方法)。
我該如何處理?我需要根據任何值生成句子> 0。起初我想,很簡單,我只需將所有值推入一個陣列,檢查 0,然后從陣列中洗掉任何等于 0 的專案。然后,根據陣列的長度構建句子,即如果陣列長度為3,則將每個值稱為array[0], array[1], array[2]。但是,這提出了一個問題,因為我需要能夠澄清句子中的哪些值。例如,如果我yellow從陣列中洗掉,陣列長度將為3,但我不知道洗掉了哪個值。
誰能幫我想出一個有效的解決方案?
uj5u.com熱心網友回復:
您可以使用簡單的for..of回圈來迭代物件的鍵和值,在其中構建您的字串。
這確實會產生一個牛津逗號,但您可以在條件中去掉它(您選擇使用它and)。
let data = {red: 100, blue: 200, yellow: 0, green: 400};
let res = 'We found '
// Keep a record of how many keys we've processed so we know when we're at the end
let i = 1
for (const [k, v] of Object.entries(data)) {
// we could just continue early here, but we want to keep adding to `i`
if (v > 0) {
// This is the last key so use `and` not a comma
if (i === Object.keys(data).length) {
res = `and ${v} ${k} posts.`
} else {
res = `${v} ${k} posts, `
}
}
i
}
console.log(res)
uj5u.com熱心網友回復:
嘗試這個
let data = {red: 100, blue: 200, yellow: 0, green: 400};
let str = [];
let len = Object.keys(data).length;
Object.entries(data).forEach(([key, val], index) => {
let isLast = (len - 1 == index) && str.length > 0;
if(val > 0) str.push((isLast ? 'and ' : '') `${val} ${key} posts`);
})
let resultsSentence = 'We found ' str.join(', ')
console.log(resultsSentence)
uj5u.com熱心網友回復:
試試這個(沒有依賴)
const keys = Object.keys(data)
const values = Object.values(data)
let string = 'we found'
values.map((item, index)=>{
if(item > 0){
string = ` ${item} ${keys[index]} posts,`
}
})
console.log(string.slice(0,-1) '.')
嘗試使用 lodash 作為
const _ = require('lodash')
let data = {red: 100, blue: 200, yellow: 0, green: 400};
let string = 'we found'
_.map(data,(value,key)=>{
if(value > 0){
string = ` ${value} ${key} posts,`
}
})
console.log(string.slice(0,-1) '.')
uj5u.com熱心網友回復:
可能是你有一個過時的瀏覽器。
我在 Chrome 版本 102.0.5005.63(官方構建)(64 位)上測驗了您的代碼
let data = {red: 100, blue: 200, yellow: 0, green: 400};
let resultsSentence = `We found ${data.red} red posts, ${data.blue} blue posts, and ${data.green} green posts.`
console.log(resultsSentence);
并得到了這個結果:
We found 100 red posts, 200 blue posts, and 400 green posts.
因此,除非我不理解您的問題,否則當我們包含data訪問其屬性的物件時沒有錯誤。
讓我知道。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485353.html
標籤:javascript 目的
