5.6 invert
5.6.1 语法:
_.invert(list)
5.6.2 说明:
对list对象中的属性名和属性值进行互换,并返回一个对象(属性值必须为唯一的,否则将使用最后一个重复的属性)
5.6.3 代码示例:
var result;
// 操作数组
result = _.invert(['a', 'b']);
console.log(result) //=> {a: "0", b: "1"}
// 操作对象
result = _.invert({ one: 1, two: 2, three: 3});
console.log(result) //=> {1: "one", 2: "two", 3: "three"}
// 函数
function Stor() {
this.one = 1;
}
Stor.prototype.two = 2; //通过给Stor对象的prototype属性给Stor对象添加一个two属性
result = _.invert(new Stor);
console.log(result) //=> {1: "one"}
5.6.4 操作非对象、数组会返回什么呢?
var result;
result = _.invert('123');
console.log(result) //=> {}
result = _.invert(null);
console.log(result) //=> {}
关于操作字符串,之前学的方法中大部分都是将字符串转为数组,此方法将不会将字符串转换为数组操作。
5.6.5 属性值并非字符串而是一个方法的情况会返回什么呢?
var obj = { one: function () { }, two: 2 }
var result = _.invert(obj);
console.log(result) //=> {2: "two", function () { }: "one"}
5.6.6 重复的属性值
// 操作对象
var result = _.invert({ one: 1, two: 2, three: 3, four: 3});
console.log(result) //=> {1: "one", 2: "two", 3: "four"}
5.6.7 call方法后的会转换吗?
function Stor() {
this.one = 1;
}
function Bar() {
Stor.call(this);
this.two = 2;
}
var result = _.invert(new Bar);
console.log(result) //=> [1, 2]