一,for in迴圈
let obj = {
id: 1,
name: 'rosnewang',
age: 20
}
for(let key in obj){
console.log(key + '---' + obj[key])
}
// id --- 1
name --- rosenwang
age --- 20
複製程式碼
二,Object.keys()和Object.values()
在實際開發中,我們有時需要知道物件的所有屬性,原生js給我們提供了一個很好的方法:Object.keys(),該方法返回一個陣列。
傳入物件, 返回 包含物件可列舉屬性和方法的陣列
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]建構函式 返回空陣列或者屬性名複製程式碼
建構函式,返回空陣列或者屬性名
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"]
複製程式碼
陣列,返回索引
var arr = ["a", "b", "c"];
console.log(Object.keys(arr)); // console: ["0", "1", "2"]
複製程式碼
如何判斷一個物件是否為空
Object.keys(obj).length,通過物件的可列舉屬性的個數來判斷
遍歷key:Object.keys()
遍歷值:Object.values()
遍歷Key和值:Object.entries
更多關於物件屬性的遍歷方法點選這裡