js 遍历对象属性(for in、Object.keys、Object.getOwnProperty) 以及高效地输出 js 数组
js中几种遍历对象的方法,包括for in、Object.keys、Object.getOwnProperty,它们在使用场景方面各有不同。
for in
主要用于遍历对象的可枚举属性,包括自有属性、继承自原型的属性
var obj = {"name":"Poly", "career":"it"} Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false}); Object.prototype.protoPer1 = function(){console.log("proto");}; Object.prototype.protoPer2 = 2; console.log("For In : "); for(var a in obj) console.log(a);
Object.keys
返回一个数组,元素均为对象自有的可枚举属性
var obj = {"name":"Poly", "career":"it"} Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false}); Object.prototype.protoPer1 = function(){console.log("proto");}; Object.prototype.protoPer2 = 2; console.log("Object.keys:") console.log(Object.keys(obj));
Object.getOwnProperty
用于返回对象的自有属性,包括可枚举和不可枚举的
var obj = {"name":"Poly", "career":"it"} Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false}); Object.prototype.protoPer1 = function(){console.log("proto");}; Object.prototype.protoPer2 = 2; console.log("Object.getOwnPropertyNames: "); console.log(Object.getOwnPropertyNames(obj));
输出如下:
怎样快速而优雅地遍历 JavaScript 数组
// 最快且优雅的代码 var array = [0,1,2,3,4,5,6,7,8,9]; // while 循环 var i = array.length; while (i–-) { fn(array[i]); }