按书上的样例,慢慢理解。
其实,JAVASCRIPT也应该可以写出正规点的,封装性好的代码。
<html> <body> <script type="text/javascript"> function findLivingCats() { var livingCats = {"Spot": true, "Noog": false, "Biech": true, "Cathy": false, }; var mailArchive = ["died 06/12/2002 (mother Yellow Bess): Cathy Hobbles the 2nd, Cathy", "born 20/09/2004 (mother Yellow Bess): Noog Hobbles the 2nd, Noog", "born 12/11/2012 (mother Yellow Bess): Biech Hobbles the 2nd, Biech", ]; function startsWith(str, pattern) { return str.slice(0, pattern.length) == pattern; } function catNames(paragraph) { var colon = paragraph.indexOf(":"); console.log("colon: ", colon); console.log("return: ", paragraph.slice(colon + 2).split(", ")); return paragraph.slice(colon + 2).split(", "); } function addToSet(set, values) { for (var i = 0; i < values.length; i++) set[values[i]] = true; } function removeFromSet(set, values) { for (var i = 0; i < values.length; i++) delete set[values[i]]; } function handleParagraph(paragraph) { if (startsWith(paragraph, "born")) { addToSet(livingCats, catNames(paragraph)); } else if(startsWith(paragraph, "died")) { removeFromSet(livingCats, catNames(paragraph)); } } for (var mail = 0; mail < mailArchive.length; mail++) { var paragraphs = mailArchive[mail].split("\n"); for (var i = 0; i < paragraphs.length; i++) { handleParagraph(paragraphs[i]); } } return livingCats; } var howMany = 0; for (var cat in findLivingCats()) howMany++; console.log("There are currently ", howMany, " cats alive.") </script> </body> </html>