javascript 数组 排除null, undefined, 和不存在的元素
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript 数组 排除null, undefined, 和不存在的元素,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1959字,纯文字阅读大概需要3分钟。
内容图文
The most common way to loop through the elements of an array is with a for loop:
var o = [1,2,3,4,5]
var keys = Object.keys(o); // Get an array of property names for object o
var values = [] // Store matching property values in this array
for(var i = 0; i < keys.length; i++) { // For each index in the array
var key = keys[i]; // Get the key at that index
values[i] = o[key]; // Store the value in the values array
}
In nested loops, or other contexts where performance is critical, you may sometimes
see this basic array iteration loop optimized so that the array length is only looked up
once rather than on each iteration:
for(var i = 0, len = keys.length; i < len; i++) {
// loop body remains the same
}
These examples assume that the array is dense and that all elements contain valid data.
If this is not the case, you should test the array elements before using them. If you want
to exclude null, undefined, and nonexistent elements, you can write this:
for(var i = 0; i < a.length; i++) {
if (!a[i]) continue; // Skip null, undefined, and nonexistent elements
// loop body here
}
If you only want to skip undefined and nonexistent elements, you might write:
for(var i = 0; i < a.length; i++) {
if (a[i] === undefined) continue; // Skip undefined + nonexistent elements
// loop body here
}
Finally, if you only want to skip indexes for which no array element exists but still want
to handle existing undefined elements, do this:
for(var i = 0; i < a.length; i++) {
if (!(i in a)) continue ; // Skip nonexistent elements
// loop body here
}
You can also use a for/in loop (§5.5.4) with sparse arrays. This loop assigns enumerable property names (including array indexes) to the loop variable one at a time.
Indexes that do not exist will not be iterated:
for(var index in sparseArray) {
var value = sparseArray[index];
// Now do something with index and value
}
原文:http://www.cnblogs.com/facial/p/5144698.html
内容总结
以上是互联网集市为您收集整理的javascript 数组 排除null, undefined, 和不存在的元素全部内容,希望文章能够帮你解决javascript 数组 排除null, undefined, 和不存在的元素所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。