我在這里找到了一個很好的例子,展示了如何通過條件查看 arrayObjects,但我有一個問題。
每次條件為假時,它的console.logging 就是這樣。是否可以在完成所有內容的回圈后只執行一次 console.log。
var arrayObjects = [{
"building": "A",
"status": "good"
},
{
"building": "B",
"status": "horrible"
}
];
for (var i = 0; i < arrayObjects.length; i ) {
console.log(arrayObjects[i]);
for (key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
console.log(key "->" arrayObjects[i][key]);
} else {
console.log("nothing found");
}
}
}
uj5u.com熱心網友回復:
只需.length與 if 條件一起使用。
var arrayObjects = [{
"building": "A",
"status": "good"
},
{
"building": "B",
"status": "horrible"
}
];
for (var i = 0; i < arrayObjects.length; i ) {
console.log(arrayObjects[i]);
if( i === arrayObjects.length-1 ) {
console.log("nothing found");
}
}
uj5u.com熱心網友回復:
我假設您希望Nothing found在沒有真正找到任何東西時列印它,甚至沒有找到任何東西..
那么,你可以試試這個。
var arrayObjects = [{"building":"A", "status":"good"},
{"building":"B","status":"horrible"}];
var isFound = false;
for (var i=0; i< arrayObjects.length; i ) {
console.log(arrayObjects[i]);
for(key in arrayObjects[i]) {
if (key == "status" && arrayObjects[i][key] == "good") {
isFound = true
console.log(key "->" arrayObjects[i][key]);
}
}
}
if (isFound === false){
console.log("nothing found");
}
uj5u.com熱心網友回復:
您可以使用陣列的someorfilter方法。
var arrayObjects = [{"building":"A", "status":"good"},
{"building":"B","status":"horrible"}];
const found = arrayObjects.some(it => it.status === 'good')
if (found) {
console.log('found')
}
const items = arrayObjects.filter(it => it.status === 'good')
if (items.length) {
console.log('found')
}
uj5u.com熱心網友回復:
另一種宣告方式解決方案:
var arrayObjects = [{
"building": "A",
"status": "good"
},
{
"building": "B",
"status": "horrible"
}
];
const chechCondition = (arr, key = 'status', value ='good') => {
const result = arr.find((obj) => obj[key] === value);
return result
? `${key} -> ${result[key]}`
: "nothing found";
};
console.log(chechCondition(arrayObjects)); //status -> good
console.log(chechCondition(arrayObjects, 'building', 'B')); //building -> B
console.log(chechCondition(arrayObjects, 'building', 'C')); //nothing found
uj5u.com熱心網友回復:
如果你愿意重構你的代碼,你可以通過只使用一個回圈來節省時間復雜度 Array.reduce()
var arrayObjects = [{
"building": "A",
"status": "good"
},
{
"building": "B",
"status": "horrible"
}
];
const foundKeys = arrayObjects.reduce((bool, key) => {
console.log(key)
if (key.status === "good") {
console.log("status ->", key.status);
bool = true
}
return bool
}, false)
if (!foundKeys) {
console.log("Nothing found")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/334101.html
標籤:javascript
