Home > Web Front-end > JS Tutorial > Summary of various methods of Object in JavaScript (with examples)

Summary of various methods of Object in JavaScript (with examples)

不言
Release: 2019-01-29 09:42:21
forward
2391 people have browsed it

This article brings you a summary of various methods of Object in JavaScript (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. hasOwnProperty

obj.hasOwnProperty(prop)

Parameter

prop: The attribute string name to be detected or Symbol

Return value

Boolean used to determine whether an object contains the specified property

All objects that inherit Object will inherit the hasOwnProperty() method. This method is used to detect whether an object contains specific properties of its own. Unlike the in operator, this method ignores properties inherited from the prototype chain

Object.prototype.a = 'aaa';
var obj = {
  b: 'bbb'
}
console.log(obj.hasOwnProperty(a)); // false
for(var item in obj) {
  console.log(item); // b  a。此结果也找到了从原型链上继承过来的属性
}
Copy after login

If hasOwnProperty is used as the property name

var foo = {
  hasOwnProperty: function() {
    return false
  },
  bar: 'bar'
}

foo.hasOwnProperty('bar'); // false
// 如果这种情况下,想调用原型链上的方法
({}).hasOwnProperty.call(foo, 'bar'); // 即foo对象调用了{}对象的方法。
// 等同于
Object.prototype.hasOwnProperty.call(foo, 'bar')
Copy after login

Extension: Traverse all properties of an object

for ... in will only loop over enumerable properties, so you should not loop over non-enumerable properties based on this.

2.getOwnPropertyNames

Object.getOwnPropertyNames(obj)

Parameters

obj An object with its own enumerable and non-enumerable properties The name is returned.

Return value

The string array corresponding to the own properties found on the given object.

Object.getOwnPropertyNames() returns an array containing enumerable and non-enumerable properties in obj.

3.Object.keys()

Object.keys(obj)

Parameters

To return the object that enumerates its own properties

Return value

A string array representing all enumerable properties of the given object

Description

Object.keys() returns a string array whose elements are characters An array of strings whose elements come from directly enumerable properties of the given object. The order of these properties is consistent with manually traversing the property (for...in...).

var obj = {a:'a',b:'b',c:'c'};
console.log(Object.keys(obj));// ['a', 'b', 'c']
Copy after login

4.Object.values()

Object.keys() returns the key value, Object.values() returns the value value, the rules are the same as Object.keys().

5.Object.assign()

Object.assign() is used to copy all enumerable values ​​from one object to the target object. It will return the target object.

Object.assign(target, ...sources);

Description

If the properties in the target object have the same properties as those in the source object. The properties in the target object will be overwritten. Properties of String type and Symbol type will be copied.
In the case of an error, for example if the property is not writable, a TypeError is raised, and the target object can be changed if any properties were added before the error was raised.

const a = {a: 'a', b: 'b'};
var b = Object.assign({}, a);
console.log(b); //{a: 'a', b: 'b'}
Copy after login

Deep copy, Object.assign() can only copy the properties of the first layer of the object. If the source object's property value is a reference to the object, it only copies that reference value.

  let obj1 = { a: 0 , b: { c: 0}};
  let obj2 = Object.assign({}, obj1);
  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
  
  obj1.a = 1;
  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}
  
  obj2.a = 2;
  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}}
  
  obj2.b.c = 3;
  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}}
  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}}
  
  // Deep Clone
  obj1 = { a: 0 , b: { c: 0}};
  let obj3 = JSON.parse(JSON.stringify(obj1));
  obj1.a = 4;
  obj1.b.c = 4;
  console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}}
Copy after login

Merge objects

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, 注意目标对象自身也会改变。
Copy after login

Merge objects with the same properties, and the properties are overwritten by other objects with the same properties in subsequent parameters.

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
Copy after login

Copy attributes of symbol type

var o1 = { a: 1 };
var o2 = { [Symbol('foo')]: 2 };

var obj = Object.assign({}, o1, o2);
console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
Copy after login

Inherited properties and non-enumerable properties cannot be copied

var obj = Object.create({foo: 1}, { // foo 是个继承属性。
    bar: {
        value: 2  // bar 是个不可枚举属性。
    },
    baz: {
        value: 3,
        enumerable: true  // baz 是个自身可枚举属性。
    }
});

var copy = Object.assign({}, obj);
console.log(copy); // { baz: 3 }
Copy after login

The original type will be packaged as an object

var v1 = "abc";
var v2 = true;
var v3 = 10;
var v4 = Symbol("foo")

var obj = Object.assign({}, v1, null, v2, undefined, v3, v4); 
// 原始类型会被包装,null 和 undefined 会被忽略。
// 注意,只有字符串的包装对象才可能有自身可枚举属性。
console.log(obj); // { "0": "a", "1": "b", "2": "c" }
Copy after login

Exception will interrupt subsequent copy tasks

var target = Object.defineProperty({}, "foo", {
    value: 1,
    writable: false
}); // target 的 foo 属性是个只读属性。

Object.assign(target, {bar: 2}, {foo2: 3, foo: 3, foo3: 3}, {baz: 4});
// TypeError: "foo" is read-only
// 注意这个异常是在拷贝第二个源对象的第二个属性时发生的。

console.log(target.bar);  // 2,说明第一个源对象拷贝成功了。
console.log(target.foo2); // 3,说明第二个源对象的第一个属性也拷贝成功了。
console.log(target.foo);  // 1,只读属性不能被覆盖,所以第二个源对象的第二个属性拷贝失败了。
console.log(target.foo3); // undefined,异常之后 assign 方法就退出了,第三个属性是不会被拷贝到的。
console.log(target.baz);  // undefined,第三个源对象更是不会被拷贝到的。
Copy after login

Copy accessor

var obj = {
  foo: 1,
  get bar() {
    return 2;
  }
};

var copy = Object.assign({}, obj); 
// { foo: 1, bar: 2 }
// copy.bar的值来自obj.bar的getter函数的返回值 
console.log(copy); 

// 下面这个函数会拷贝所有自有属性的属性描述符
function completeAssign(target, ...sources) {
  sources.forEach(source => {
    let descriptors = Object.keys(source).reduce((descriptors, key) => {
      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
      return descriptors;
    }, {});

    // Object.assign 默认也会拷贝可枚举的Symbols
    Object.getOwnPropertySymbols(source).forEach(sym => {
      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
      if (descriptor.enumerable) {
        descriptors[sym] = descriptor;
      }
    });
    Object.defineProperties(target, descriptors);
  });
  return target;
}

var copy = completeAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }
Copy after login

The above is the detailed content of Summary of various methods of Object in JavaScript (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template