本文實例講述了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=>ah23.js:4 1=>bh23.js:4 2=>ch23.js:4 3=>dh23.js:4 4=>eh23.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=>ah23.js:9 1=>bh23.js:9 2=>ch23.js:9 3=>dh23.js:9 4=>eh23.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=>ah23.js:17 1=>bh23.js:17 3=>dh23.js:17 4=>e*/</script>
運行效果:
這種方式遍歷跳過undefined值
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答