有的时候,我们需要操作Object中的key和value,我们需要获取对应的所有keys或者values
先看看prototype的api设计吧:
/*
获取keys
*/
keys:function(obj){
var keys = [];
for(var pro in obj){
keys.push(pro);
}
return keys;
}
/*
获取values
*/
values:function(obj){
var values = [];
for(var pro in obj){
values.push(obj[pro]);
}
return values;
}
1、获取Object对应的keys
/*
*keys-get a array contains all the keys in object*
*@function*
*@param {Object} source*
*@return {Array}*
*@mark we have not check the source is or not object*
*/
ZYC.object.keys = function(source){
var result=[],
key,
_length=0;
for(key in source){
if(source.hasOwnProperty(key)){
result[_length++] = key;
}
}
return result;
};
2、获取Object对应的values
/*
*values-get a array contains all the values in object*
*@function*
*@param {Object} source*
*@return {Array}*
*@mark we have not check the source is or not object*
*/
ZYC.object.values = function(source){
var result=[],key,_length=0;
for(key in source){
if(source.hasOwnProperty(key)){
result[_length++] = source[key];
}
}
return result;
};

本文介绍了如何通过自定义函数获取Object对象中的所有keys和values,包括使用prototype api设计实现的示例。
1766

被折叠的 条评论
为什么被折叠?



