javascript - Try to put space between items with splice function but when reload page crash (javascript)
问题描述
I want to put space between the items of an array but when I reload the webpage it crash
Here's part of the code:
array = ['a', 'b', '2', 'c'];
for(i = 0; i < array.length; i++){
if(array[i + 1] === '2'){
array.splice(i + 2, 0, ' ');
}else{
array.splice(i + 1, 0, ' ');
}
}
解决方案
You have infinite loop in your code; You are iterating not over original array, but the array you modify with each loop pass. Consider changing your code into:
array = ['a', 'b', '2', 'c'];
len = array.length;
for(i = 0; i < len ; i++){
if(array[i + 1] === '2'){
array.splice(i + 2, 0, ' ');
}else{
array.splice(i + 1, 0, ' ');
}
推荐阅读
- angular - 在 JSON 中转换对象数组元素
- react-native - setState 第二次出错后导航到另一个页面
- java - Wiremock 服务器无法将录音存储在指定目录中
- sql - Postgres重叠日期查询 - 查看两个日期作为一个范围是否重叠一个月
- python - 如何获得满足特定条件的 Dataframe 的一部分?
- fortran - Fortran 中的浮点运算
- wso2 - 两个网关工作人员可以将节流数据发布到一个流量管理器节点吗
- android - 无法将 Firebase 添加到 LibGDX 项目
- azure - 当 Windows 服务停止时,如何在 OMS 中创建警报?
- java - svnant 更新单个文件并跳过错误