# 章序号/节序号/节/笔记序号 codecademy,loops # 概念阐释 ## 语义 `break`关键字会终止当前的循环,并继续执行循环体之外接下来的代码。 ## 语法 ```js break [label]; ``` # 举例子 ## 在 switch 条件中 ```js const food = "sushi"; switch (food) { case "sushi": console.log("Sushi is originally from Japan."); break; case "pizza": console.log("Pizza is originally from Italy."); break; default: console.log("I have never heard of that dish."); break; } ``` ## 在循环中 # 类比、比较与对比 # 问题 1. Add a `break` inside your loop’s block that breaks out of the loop if the element at the current index in the `rapperArray` is `'Notorious B.I.G.'`. Log the element before breaking out of the loop.如果 `rapperArray` 中当前索引处的元素为`“Notorious B.I.G.”`,则在循环块内添加一个中断,以中断循环。在退出循环之前记录元素。(print `"Lil' Kim", "Jay-Z", "Notorious B.I.G."`) ```js const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"]; ``` 2. 解释代码 ```html <label for="search">Search by contact name: </label> <input id="search" type="text"> <button>Search</button> <p></p> ``` ```js const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975']; const para = document.querySelector('p'); const input = document.querySelector('input'); const btn = document.querySelector('button'); btn.addEventListener('click', function() { let searchName = input.value.toLowerCase(); input.value = ''; input.focus(); for (let i = 0; i < contacts.length; i++) { let splitContact = contacts[i].split(':'); if (splitContact[0].toLowerCase() === searchName) { para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.'; break; } else if (i === contacts.length - 1) { para.textContent = 'Contact not found.'; } } }); ``` # 问题答案 ```js const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"]; for(let i =0; i<=rapperArray.length; i++){ if(rapperArray[i] === 'Tupac'){ break; } console.log(`${i}:${rapperArray[i]}`)// 可以看到循环和单词的关系 }; ``` - *为什么console在循环中的位置不同,得到的结果不同?* - 可以把数组转换为数字,更简单理解; - `rapperArray.length` 等于4; - ` i `相当于是数组的未知数符号,一般情况下访问数组`数组名[indexnumber]`, 但在执行的循环语句中,`i` 代表每次执行迭代语句时的`index`,在这里是`0,1,2,3`; - `console`在循环的开始,先执行console的初始值,这里是`0=Lil' Kim`,再执行`break`,结果为`0,1,2` - `console`在后,先执行`break`,`rapperArray[i]==='Notorious B.I.G.'`时停止,结果为`0,1` # 备注(经验集/错误集) ## 经验集 ## 错误集 - 对于loop和globe scoop 数组的概念不清楚,经常忘记要循环数组时要用`array[i]`, i为数组元素,print时也是返回数组元素。*`array[i]`表示`array[index]`* ## 参考资料 - [break](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/break)