typescript - 为什么这个 for 循环不在打字稿函数中执行?
问题描述
我不明白为什么这个函数中的 for 循环永远不会运行。我在每个控制台日志旁边写了返回的内容。谁能帮我弄清楚为什么?
export function arrayChange(inputArray: number[]): number {
let total = 0;
console.log('inputArray.length', inputArray.length) // returns 3
console.log('inputArr', inputArray[0] <= inputArray[1]) //returns true
for(let i = 0; i > inputArray.length - 1; i++){
console.log('hello') //never runs
if(inputArray[i] <= inputArray[i + 1]){
total += inputArray[i + 1] - inputArray[i] + 1
}
}
return total
}
console.log(arrayChange([1, 3, 4])); //returns 0
解决方案
你有你的条件倒退:
for(let i = 0; i > inputArray.length - 1; i++){
}
你的数组长度为 3,所以你开始的是:
for(let i = 0; i > 3 - 1; i++)
i
因此永远不会大于 2。因此循环不会进行单次迭代。
你可能是这个意思(注意小于,而不是大于):
for(let i = 0; i < inputArray.length - 1; i++){
}
你现在从这个开始:
for(let i = 0; i < 3 - 1; i++) // 0 < 2 - first loop iteration
for(let i = 0; i < 3 - 1; i++) // 1 < 2 - second loop iteration
for(let i = 0; i < 3 - 1; i++) // 2 < 2 - no more iteration!
假设您要实际迭代所有数组元素而不跳过最后一个,我们还没有完成。
这意味着条件仍然错误(使用<=
或保留- 1
):
for(let i = 0; i < inputArray.length; i++){
}
for(let i = 0; i < 3; i++) // 0 < 3 - first loop iteration
for(let i = 0; i < 3; i++) // 1 < 3 - second loop iteration
for(let i = 0; i < 3; i++) // 2 < 3 - third loop iteration
因此,您已经迭代了所有 (3) 个数组元素。
推荐阅读
- r - 条件匹配时滞后于 R
- python - 注册 Key_acute 事件在第一次按键时不起作用
- python - 有人知道模仿 TradingView 编辑器的 Python 脚本吗?
- reactjs - Firebase 和 React:CollectionReference.doc() 参数类型
- error-handling - 在 SAS Studio 中访问 SASHELP.ZIPCODE.DATA 的错误代码
- firebase - I/flutter (22027):MissingPluginException(在通道 plugins.flutter.io/cloud_firestore 上找不到方法 DocumentReference#setData 的实现)
- java - Spring MVC 在 WAR 和 JAR 文件中带有 jsp 文件
- php - 试图验证 JWT 签名 Tymon/jwt-auth laravel
- python - 使用 BeautifulSoup Python 进行 Web 抓取返回 None
- r - R:基于超过 1 个变量对记录进行分类