JavaScript

超轻量级php框架startmvc

js实现for循环跳过undefined值示例

更新时间:2020-09-02 19:06:01 作者:startmvc
本文实例讲述了js实现for循环跳过undefined值的方法。分享给大家供大家参考,具体如下:<

本文实例讲述了js实现for循环跳过undefined值的方法。分享给大家供大家参考,具体如下:


<script>
var narr=['a','b','c','d','e'];
console.log(narr);
for (var j=0;j<narr.length;j++){
 console.log(j+'=>'+narr[j]);
};
console.log(narr);
for (var j=0;j<narr.length;j++){
 console.log(j+'=>'+narr[j]);
 if (narr[j] == 'c'){
 //narr.splice(j,1);
 delete narr[j];
 };
};
console.log(narr);
for (var j in narr){
 console.log(j+'=>'+narr[j]);
};
/*
(5) ["a", "b", "c", "d", "e"]0: "a"1: "b"3: "d"4: "e"length: 5__proto__: Array(0)
h23.js:4 0=>a
h23.js:4 1=>b
h23.js:4 2=>c
h23.js:4 3=>d
h23.js:4 4=>e
h23.js:7 (5) ["a", "b", "c", "d", "e"]0: "a"1: "b"3: "d"4: "e"length: 5__proto__: Array(0)
h23.js:9 0=>a
h23.js:9 1=>b
h23.js:9 2=>c
h23.js:9 3=>d
h23.js:9 4=>e
h23.js:15 (5) ["a", "b", empty, "d", "e"]0: "a"1: "b"3: "d"4: "e"length: 5__proto__: Array(0)
h23.js:17 0=>a
h23.js:17 1=>b
h23.js:17 3=>d
h23.js:17 4=>e
*/
</script>

运行效果:

这种方式遍历跳过undefined

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。

PS:这里再为大家推荐一款JS数组遍历方式分析对比工具供大家参考:

在线JS常见遍历方式性能分析比较工具:http://tools.jb51.net/aideddesign/js_bianli

js for循环 跳过 undefined值