for in / for of / Object.keys() / Object.values()

引用1:https://www.cnblogs.com/wujie520303/p/4931384.html
引用2:MDN for...in
引用3:MDN for...of
引用4:MDN Object.keys()
引用5:MDN Object.values()

for in for of Object.keys() Object.values()
遍历对象的属性(不建议使用for in来迭代数组) 在可迭代对象( Array,Map,String 等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句 返回当前对象的自身可枚举属性组成的数组 Object.values()返回一个数组,其元素是在对象上找到的可枚举属性值
var triangle = {a: 1, b: 2, c: 3};

function ColoredTriangle() {
  this.color = 'red';
}

ColoredTriangle.prototype = triangle;

var obj = new ColoredTriangle();

for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) {   //hasOwnProperty继承的属性不显示。eslint建议用这种格式,不然会报警
    console.log(`obj.${prop} = ${obj[prop]}`);
  } 
}

// Output:
// "obj.color = red"
/*for of 迭代 array*/
let iterable = [10, 20, 30];

for (let value of iterable) {
    value += 1;
    console.log(value);
}
// 11
// 21
// 31
/*Object.keys()*/

let obj = {name:"某某某",age:22,address:"new york",handlePerson:()=>{}};
 
Object.keys(obj);             

// 打印结果: ["name", "age", "address", "handlePerson"]
var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// array like object with random key ordering
// when we use numeric keys, the value returned in a numerical order according to the keys
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']
posted @ 2020-09-29 16:26  bcj7wi3kd5h1wd6  阅读(146)  评论(0编辑  收藏  举报