Object对象常用方法

ゝ一纸荒年。 2023-05-21 07:24 77阅读 0赞

Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for…in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环还会枚举原型链中的属性)。

  1. const object3 = {
  2. a: 'somestring',
  3. b: 42
  4. };
  5. console.log(Object.entries(object3));//[[a: 'somestring'],[b: 42]]
  6. for (let [key, value] of Object.entries(object3)) {
  7. console.log(`${ key}: ${ value}`);
  8. }
  9. // "a: somestring"
  10. // "b: 42"

Object.fromEntries() 方法把键值对列表转换为一个对象。

  1. const entries = new Map([
  2. ['foo', 'bar'],
  3. ['baz', 42]
  4. ]);
  5. const obj = Object.fromEntries(entries);
  6. console.log(obj);
  7. // expected output: Object { foo: "bar", baz: 42 }

Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。

  1. const target = { a: 1, b: 2 };
  2. const source = { b: 4, c: 5 };
  3. const returnedTarget = Object.assign(target, source);//sourc复制到target对象,并与target对象和合并,然后返回target
  4. console.log(target);
  5. // expected output: Object { a: 1, b: 4, c: 5 }
  6. console.log(returnedTarget);
  7. // expected output: Object { a: 1, b: 4, c: 5 }

Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for…in 循环遍历该对象时返回的顺序一致 。

  1. var arr = ['a', 'b', 'c'];
  2. console.log(Object.keys(arr)); // console: ['0', '1', '2']
  3. // array like object
  4. var obj = { 0: 'a', 1: 'b', 2: 'c' };
  5. console.log(Object.keys(obj)); // console: ['0', '1', '2']
  6. // array like object with random key ordering
  7. var anObj = { 100: 'a', 2: 'b', 7: 'c' };
  8. console.log(Object.keys(anObj)); // console: ['2', '7', '100']
  9. // getFoo is a property which isn't enumerable var myObj = Object.create({}, { getFoo: { value: function () { return this.foo; } } }); myObj.foo = 1; console.log(Object.keys(myObj)); // console: ['foo']

Object.values()返回一个数组,其元素是在对象上找到的可枚举属性值。属性的顺序与通过手动循环对象的属性值所给出的顺序相同。

  1. var obj = { foo: 'bar', baz: 42 };
  2. console.log(Object.values(obj)); // ['bar', 42]
  3. // array like object
  4. var obj = { 0: 'a', 1: 'b', 2: 'c' };
  5. console.log(Object.values(obj)); // ['a', 'b', 'c']
  6. // array like object with random key ordering
  7. // when we use numeric keys, the value returned in a numerical order according to the keys
  8. var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
  9. console.log(Object.values(an_obj)); // ['b', 'c', 'a']
  10. // getFoo is property which isn't enumerable var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } }); my_obj.foo = 'bar'; console.log(Object.values(my_obj)); // ['bar'] // non-object argument will be coerced to an object console.log(Object.values('foo')); // ['f', 'o', 'o']

发表评论

表情:
评论列表 (有 0 条评论,77人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Object方法

    1.clone方法 保护方法,实现对象的浅复制,只有实现了Cloneable接口才可以调用该方法,否则抛出CloneNotSupportedException异常。 2.g