javascript方法名称的获取以及Object.Keys应用

对象赋值可以是下面这种方式:

var properties={
	"width":"100px",
	"height":"200px"
};
这个时候如果我要获取width的值,可以利用properties.width或者properties["width"]获取。

有一种情况,如果我要获取"width"这个名称,怎么获取。

var properties={
	"width":"100px",
	"height":"200px"
};
for (var prop in properties) {
	alert(prop+"-"+properties[prop]);
}
jQuery中css()等其它方法的遍历属性都是这种方式。

稍微整理下:

;(function(jQuery){
	jQuery.extend({
		/**
		 * 描述:获取样式表中的样式名称以及对应的样式值,以数组的形式返回
		**/
		Properties:function(properties){
			var //属性对象集合
				props = [], 
				//属性名称集合
				names = [],
				len = 0;
			for(var prop in properties) {
				names[len]=prop;
				props[names[len]]=properties[prop];
				len++;
			}
			return {
				names: names,
				props: props
			}
		}
	});
})(jQuery);
var names=jQuery.Properties({"width":"100px","height":"200px"}).names;
for(var i=0;i<names.length;i++){
	alert(names[i]);
}

方法2:利用object.keys也可以解决。作用是返回可以枚举属性和方法的名称。

<script type="text/javascript">
	var properties={  
		"width":"100px",  
		"height":"200px"  
	};  
	jQuery.Properties = function(properties){
		var names = Object.keys(properties),
			props = [];
		for(var i=0,maxLen=names.length;i<maxLen;i++) {
			props[names[i]] = properties[names[i]];
		}
		return {
			names : names,
			props : props
		}
	};
	var names = jQuery.Properties(properties).names;
	for(var i=0;i<names.length;i++){
		alert(names[i]);
	}
</script>
当然这个对function也同样适用。  

<script type="text/javascript">
	function Person(name,password){
		this.name = name;
		this.password = password;
		this.hello = function(){
			alert("Hello!");
		}
	}
	Person.Prototype = {
		introduce:function(){
			alert("Hello,My name is :"+this.name);
		}
	}
	jQuery.Properties = function(properties){
		var names = Object.keys(properties),
			props = [];
		for(var i=0,maxLen=names.length;i<maxLen;i++) {
			props[names[i]] = properties[names[i]];
		}
		return {
			names : names,
			props : props
		}
	};
	var student = new Person('admin','123456'),
		properties = jQuery.Properties(student),
		names = properties.names,
		props = properties.props;
	for(var i=0;i<names.length;i++){ //原型链上的introduce这个方法不能获取到
		alert(names[i]+"-"+props[names[i]]);
	}
</script>

方法3:利用Object.getOwnPropertyNames(),它会以数组的形式返回对象自己的属性名称。(类似Object.keys)。

Object.getOwnPropertyNames():它会返回可枚举和不可枚举的属性和方法的名称。

Object.keys():它只会返回可枚举的属性和方法的名称。

但是都不能取到原型链上的属性名称。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值