const idx = todos.findIndex(item => item.completed);
if (idx !== -1) document.getElementById("check"+(idx+1)).checked = true;
or just forEach:let idx = -1;
todos.forEach(function(item,i) { if (item.completed) { idx = i; return false }})
if (idx !== -1) document.getElementById("check"+(idx+1)).checked = true;
todos.forEach(function(item,i) { document.getElementById("check"+(i+1)).checked = item.completed })
todos.forEach(function(item,i) { document.getElementById("check"+(i+1)).checked = item.completed })
is identical in functionality and compatibility to the more cumbersomefor (i = 0; i < todos.length; i++) {
if (todos[i].completed==true) {
document.getElementById("check"+(i+1)).checked=true;
}
}
which additionally creates the variable i in global scope because of the lack of var or let[...document.querySelectorAll("input[id^=check]")].forEach((chk,i) => chk.checked = todos[i].completed)
Or a jquery version as follows:
Open in new window
in this example, it will only select the first item that has completed = true.
Sam's example will select all items that has completed = true, but it depends on what you trying to archive.