5.1 keys

5.1.1 语法:

_.keys(list)

5.1.2 说明:

检索list拥有的可枚举属性名,并返回一个数组(继承属性则不检索)

5.1.3 代码示例:

var result;

// 操作数组
result = _.keys(['a', 'b']);
console.log(result) //=> ["0", "1"]

// 操作对象
result = _.keys({ one: 1, two: 2, three: 3});
console.log(result) //=> ["one", "two", "three"]

// 函数
function Stor() {
    this.one = 1;
}
Stor.prototype.two = 2; //通过给Stor对象的prototype属性给Stor对象添加一个two属性
result = _.keys(new Stor);
console.log(result) //=> ["one"]

5.1.4 操作非对象、数组会返回什么呢?

var result;

result = _.keys('123');
console.log(result) //=> []

result = _.keys(null);
console.log(result) //=> []

关于操作字符串,之前学的方法中大部分都是将字符串转为数组,此方法将不会将字符串转换为数组操作。

5.1.5 不可枚举的属性

var obj = { one: 1, two: 2};
Object.defineProperty(obj, 'three', { value: 3, enumerable: false }); // 此处给obj对象添加一个不可枚举的属性
var result = _.keys(obj);
console.log(result) //=> ["one", "two"]

5.1.6 操作window对象

// 操作window 将会输出可枚举的属性名
result = _.keys(window);
console.log(result) //=> ["top", "location", "document", "window", "external", "chrome", "_", "result"]

5.1.7 call方法后的属性会检索吗?

function Stor() {
    this.one = 1;
}
Stor.prototype.two = 2; //通过给Stor对象的prototype属性给Stor对象添加一个two属性
function Bar() {
    Stor.call(this);
    this.three = 3;
}
var result = _.keys(new Bar);
console.log(result) //=> ["one", "three"]