在實(shí)際開(kāi)發(fā)中,我們有時(shí)需要知道對(duì)象的所有屬性腊尚,原生js給我們提供了一個(gè)很好的方法:Object.keys()吨拗,該方法返回一個(gè)數(shù)組
傳入對(duì)象,返回屬性名
var obj = {'a':'123','b':'345'};
console.log(Object.keys(obj)); //['a','b']
var obj1 = { 100: "a", 2: "b", 7: "c"};
console.log(Object.keys(obj1)); // console: ["2", "7", "100"]
var obj2 = Object.create({}, { getFoo : { value : function () { return this.foo } } });
obj2.foo = 1;
console.log(Object.keys(obj2)); // console: ["foo"]
傳入字符串婿斥,返回索引
var str = 'ab1234';
console.log(Object.keys(obj)); //[0,1,2,3,4,5]
構(gòu)造函數(shù) 返回空數(shù)組或者屬性名
function Pasta(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.toString = function () {
return (this.name + ", " + this.age + ", " + this.gender);
}
}
console.log(Object.keys(Pasta)); //console: []
var spaghetti = new Pasta("Tom", 20, "male");
console.log(Object.keys(spaghetti)); //console: ["name", "age", "gender", "toString"]
數(shù)組 返回索引
var arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // console: ["0", "1", "2"]