[英]How can I access to the if with an array of objects?
您好,我是JS的新手,我需要測試if。
const length = notifications.length notifications.forEach((notification, index) => { if (length > 1 && index < length - 1) { toolTipText += ' ' }
換句話說,我需要聲明一個變量以輸入if。 我有這些變量,但是錯了,我不知道如何做好
const mockPropsForComponentAlternatorAndLOW = { notifications: [{ params: { subType: 'ALTERNATOR' } }, params: { subType: 'LOW' }] }
有什么建議么?
您的腳本有效。 只需刪除一些語法錯誤並指向正確的參考:
mockPropsForComponentAlternatorAndLOW.notifications.length
const mockPropsForComponentAlternatorAndLOW = { notifications: [ { params: { subType: 'ALTERNATOR' } }, { params: { subType: 'LOW' } } ] } const length = mockPropsForComponentAlternatorAndLOW.notifications.length mockPropsForComponentAlternatorAndLOW.notifications.forEach((notification, index) => { if (length > 1 && index < length - 1) { alert('in the scope now') // toolTipText += ' ' } })
您的問題相當模糊,但是如果我假設您通過附加通知文本來構建toolTipText
,並且希望每個通知文本之間都toolTipText
空格,則最小的變化是測試index > 0 && index < length
而不是length > 1 && index < length - 1
:
let toolTipText = "";
const length = notifications.length;
notifications.forEach((notification, index) => {
if (index > 0 && index < length) {
toolTipText += ' '
}
toolTipText += notification.text; // Or whatever the property is called
});
現場示例:
function buildToolTipText(notifications) { let toolTipText = ""; const length = notifications.length; notifications.forEach((notification, index) => { if (index > 0 && index < length) { toolTipText += ' ' } toolTipText += notification.text; // Or whatever the property is called }); return toolTipText; } console.log(buildToolTipText([{text: "only"}])); console.log(buildToolTipText([{text: "first"}, {text: "second"}])); console.log(buildToolTipText([{text: "first"}, {text: "second"}, {text: "third"}]));
但是 ,您可能會發現使用map
和join
更簡單:
let toolTipText = notifications.map(n => n.text).join(" ");
現場示例:
function buildToolTipText(notifications) { let toolTipText = notifications.map(n => n.text).join(" "); return toolTipText; } console.log(buildToolTipText([{text: "only"}])); console.log(buildToolTipText([{text: "first"}, {text: "second"}])); console.log(buildToolTipText([{text: "first"}, {text: "second"}, {text: "third"}]));
我不確定您要問的是什么,但不是100%知道,但是我將其解釋為“我的代碼未運行,這是怎么了?”。 您的mockPropsForComponentAlternatorAndLOW變量中存在語法錯誤。 在第二個“通知”對象周圍需要有一個“ {”和“}”,如下所示:
const mockPropsForComponentAlternatorAndLOW = {
notifications: [{
params: {
subType: 'ALTERNATOR'
}
},
{
params: {
subType: 'LOW'
}
}]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.