标签:
//用来变对象的。可以没有value直接传list,把list变一个对象
//也可以传长度和list一样的value,来构成数组
_.object = function(list, values) {
var result = {};
for (var i = 0, length = list && list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
//获取对象的所有键集合,有原生的nativeKeys,就用原生。
//貌似ie9以下有个枚举bug,实例的toString会覆盖原型上的toString,toString就变成不可枚举了,都没试出来过。。。。
//!({toString: null}).propertyIsEnumerable(‘toString‘);
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// 所有键列出来,实例和原型的
_.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// 实例键的值组成一个数组
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
//类似map,只不过obj是对象,用iteratee迭代每个键值对,返回新数组
_.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = _.keys(obj),
length = keys.length,
results = {},
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys[index];
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
//把一个对象转变为一个[key, value]形式的数组。
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// 对象键值对互换位置,要保证键值对中值的唯一性
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
//把对象中的函数堆到一个数组中,函数名按字母a-z排序
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
//对象的扩展,扩展传入的所有属性,包括原型链
_.extend = createAssigner(_.allKeys);
////对象的扩展,扩展传入的所有属性,不包括原型链
_.extendOwn = _.assign = createAssigner(_.keys);
标签:
原文地址:http://www.cnblogs.com/wz0107/p/4977388.html