Object's related methods and three ways of js traversing objects

This article mainly shares the basic usage of the following methods. If you want to know more about these methods, please refer to MND

Table of contents

Object related methods

Object.hasOwnProperty()

Object.defineProperty()

Object.defineProperties()

Object.assign()

Usage 1: copy an object (deep copy and shallow copy)

Usage 2: Merge Objects

Object.keys()

Object.create()

Object.entries()

Object.values()

Object.freeze()

Object.is()

Three ways to traverse objects in js

1. Use for...in

2. Using for...of and Object.keys()

3. Using for...of and Object.entries()


Object related methods

Object.hasOwnProperty()

Description: The Object.hasOwnProperty() method returns a Boolean value indicating whether the object has the specified property (whether there is a specified key or index) in its own properties.

Syntax: variable name.hasOwnProperty("property name"/index);

//当变量是数组时
const arr = [4, 6, 7, 88, 99, 200];
//判断arr数组中是否有索引为4的元素  
console.log(arr.hasOwnProperty(4));//true
//判断arr数组中是否有索引为7的元素
console.log(arr.hasOwnProperty(7));//false

//当变量是对象时 属性名需要加""
const obj = {
	name: "张三",
	age: "40"
};
//判断obj对象中中是否有属性名为"name"的属性
console.log(obj.hasOwnProperty("name"));//true
//判断obj对象中中是否有属性名为"gender"的属性
console.log(obj.hasOwnProperty("gender"));//false

Object.defineProperty()

Description: The Object.defineProperties() method will directly define a new property on an object, or modify an existing property of an object, and return this object.

Syntax: Object.defineProperties(object name, property name, {value: property value, writable: true/false});

Features: Only one attribute can be added or modified at a time .

analyze:

value: attribute value; set the attribute value of the attribute name, if [value: attribute value] is not written, the attribute value corresponding to the attribute name is undefined by default.

//不写 value:属性值 时
const obj = {};
Object.defineProperty(obj, "name", {});
console.log(obj);//{name: undefined}

//写 value:属性值 时
const myObj = {};
Object.defineProperty(myObj, "name", {value: "张三"});
console.log(myObj);//{name: '张三'}

writable:true/false; Set whether the attribute is allowed to be modified, true means allowed, false means not allowed. If not specified, the default is false.

//当writable:false 或 不写 时
const obj = {};
//Object.defineProperty(obj, "name", {value: "张三"});
Object.defineProperty(obj, "name", { value: "张三", "writable": false });
console.log(obj);//{name: '张三'}

obj.name = "李四";//不能修改 这里程序不会报错 默认不做任何事
console.log(obj);//{name: '张三'}



//当writable:true时
const myObj = {};
Object.defineProperty(myObj, "name", { value: "张三", "writable": true });
console.log(myObj);//{name: '张三'}

myObj.name = "李四";//可以修改
console.log(myObj);//{name: '李四'}

In addition to value and writable, there are other attributes for setting attributes, please refer to MDN for details .

Object.defineProperties()

Description: The Object.defineProperties() method directly defines new properties or modifies existing properties on an object, and returns the object.

Syntax: Object.defineProperties(object name, { property name 1: { value1: value 1, writable: true }, property name 2: { value2: value 2, writable: false } });

Features: The usage is similar to the Object.defineProperty() method, but the syntax is slightly different. In addition, Object.defineProperties() can only add or modify one property at a time, while the Object.defineProperty() method can add or modify multiple properties at a time .

const obj = {};
Object.defineProperties(obj, {
	"name": { value: "张三", "writable": true },
	"age": { value: 20, "writable": false }
});
console.log(obj);//{name: '张三', age: 20}

obj.name = "李四";//可以修改
obj.age = "16";//不能修改 这里程序不会报错 默认不做任何事
console.log(obj);//{name: '李四', age: 20}

Object.assign()

Description: The Object.assign() method is used to assign the values ​​of all enumerable properties from one or more source objects. It will return the target object . If the attribute names are the same, later values ​​will override earlier ones.

Syntax: Object.assign(target object, source object);

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const result = Object.assign(target, source);
console.log(result);//{a: 1, b: 4, c: 5}
console.log(target);//{a: 1, b: 4, c: 5}

Usage 1: copy an object (deep copy and shallow copy)

For Object.assign(), if the property value of the object is a simple type (string, number), the new object obtained through Object.assign({}, obj); is a deep copy; if the property value is an object or other reference type, it is actually a shallow copy for this object, which is where Object.assign() needs special attention.

deep copy

const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy);//{a: 1}

obj.a = 2;//不会对copy对象有影响
console.log(copy); //{a: 1}

shallow copy

const obj = { a: { b: 1 } };
const result = Object.assign({}, obj);
console.log(result);//{a: {b: 1}}

obj.a.b = 2;//对obj有影响
console.log(result);//{a: {b: 2}}

Usage 2: Merge Objects

Note that the target object itself also changes. If the attribute names are the same, later values ​​will override earlier ones

const o1 = { a: 1, b: 4, f: 6 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = Object.assign(o1, o2, o3);
console.log(obj); // {a: 1, b: 2, f: 6, c: 3}
console.log(o1);  // {a: 1, b: 2, f: 6, c: 3}--目标对象自身也会改变

//如果不想改变原来的对象,可以使用一个空对象作为目标对象
const o1 = { a: 1, b: 4, f: 6 };
const o2 = { b: 2 };
const o3 = { c: 3 };
const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // {a: 1, b: 2, f: 6, c: 3}

Object.keys()

Description: The Object.keys() method will return an array composed of the enumerable properties of a given object. The order of the property names in the array is the same as the order returned by the normal loop traversal object.

Syntax: Object.keys(object to return to enumerate its own properties);

const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); //['0', '1', '2']

const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); //['0', '1', '2']
for (const key of Object.keys(obj)) {
	console.log(key + ":" + obj[key]);
};

const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); //['2', '7', '100']

const myObj = Object.create({}, {
	getFoo: {
		value: function () { return this.foo; }
	}
});
myObj.foo = 1;
console.log(Object.keys(myObj)); //['foo']

Notice

1. In ES5, if the parameter of this method is not an object (but a primitive value), then it will throw a TypeError.

Object.keys("foo");// TypeError: "foo" is not an object (ES5 code)

2. In ES2015, non-object parameters will be coerced into an object.

Object.keys("foo");// ["0", "1", "2"]  (ES2015 code)

Object.create()

Description: OObject.create(object name); the object.create() method creates an object, using an existing object to provide the proto of the newly created object

Syntax: Object.create(object name);

const obj = {
	name: "haha",
	isStudent: true,
	show: function () {
		console.log(this.name + this.isStudent);
	}
};
//const stu = new obj("张三", false);//报错 obj is not a constructor

const stu = Object.create(obj);
stu.name = "张三";
stu.isStudent = false;
console.log(stu);//{name: '张三', isStudent: false}
console.log(stu.show());//张三false
console.log(stu.__proto__);//{name: 'haha', isStudent: true, show: f}

Object.entries()

Description: The Object.entries() method returns an array of key-value pairs of enumerable properties of a given object itself, and its arrangement is consistent with the order returned when using the for...in loop to traverse the object (the difference is that the for-in loop is also properties in the prototype chain are enumerated).

Syntax: Object.entries(object name);

const obj = {
	a: "have",
	b: "some",
	c: "thing",
	d: "to",
	e: "do"
};
console.log(Object.entries(obj));//[['a', 'have'], ['b', 'some'], ['c', 'thing'], ['d', 'to'], ['e', 'do']]

for (const [key, value] of Object.entries(obj)) {
	console.log(key + ":" + value);
};

Object.values()

Description: The Object.values() method returns an array of all enumerable property values ​​of a given object itself. The order of the values ​​is the same as that of using the for...in loop (the difference is that in the for-in loop enumeration prototype chain Attributes).

Syntax: Object.values(object returned enumerable property values);

const obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); //['bar', 42]

const obj_ = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj_)); //['a', 'b', 'c']

const an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); //['b', 'c', 'a']

const my_obj = Object.create({}, { getFoo: { value: function () { return this.foo; } } });
my_obj.foo = 'bar';
console.log(Object.values(my_obj)); //['bar']

console.log(Object.values('foo')); //['f', 'o', 'o']

Object.freeze()

Description: The Object.freeze() method can freeze an object. A frozen object can no longer be modified; when an object is frozen, new properties cannot be added to the object, existing properties cannot be deleted, and the enumerability, configurability, and writability of the existing properties of the object cannot be modified. property, and cannot modify the value of an existing property. Additionally, the prototype of an object cannot be modified after freezing it. freeze() returns the same object as the passed parameter.

Syntax: Object.freeze(frozen object);

const obj = {
	prop: function () { },
	foo: 'bar'
};
obj.foo = 'baz';
obj.lumpy = 'woof';
delete obj.prop;

const o = Object.freeze(obj);
console.log(obj);//{foo: 'baz', lumpy: 'woof'}
console.log(o === obj);// true

// 判断是否被冻结
Object.isFrozen(obj); //true

// 现在任何改变都会失效(默认不做任何事 程序不会报错)
obj.foo = 'quux';
obj.quaxxor = 'the friendly duck';
console.log(obj);//{foo: 'baz', lumpy: 'woof'}

Object.is()

Description: The Object.is() method determines whether two values ​​are the same value.

Syntax: Object.is(value1, value2);

Object.is('foo', 'foo');     // true
Object.is(window, window);   // true

Object.is('foo', 'bar');     // false
Object.is([], []);           // false

const foo = { a: 1 };
const bar = { a: 1 };
Object.is(foo, foo);         // true
Object.is(foo, bar);         // false

Object.is(null, null);       // true

Object.is(0, -0);            // false
Object.is(0, +0);            // true
Object.is(-0, -0);           // true
Object.is(NaN, 0 / 0);       // true

Three ways to traverse objects in js

1. Use for...in

const obj = {
	name: "张三",
	age: 25,
	gender: "男",
};
for (const key in obj) {
	console.log(key+":"+ obj[key]);
};

2. Using for...of and Object.keys()

const obj = {
	name: "张三",
	age: 25,
	gender: "男",
};
//console.log(Object.keys(obj));//['name', 'age', 'gender']

for (const key of Object.keys(obj)) {
	console.log(key + ":" + obj[key]);
};

3. Using for...of and Object.entries()

const obj = {
	name: "张三",
	age: 25,
	gender: "男",
};
//console.log(Object.entries(obj));//[['name', '张三'], ['age', 25], ['gender', '男']]

// for (const item of Object.entries(obj)) {
//     console.log(item);//['name', '张三'] ['age', 25] ['gender', '男']
// };

for (const [key, value] of Object.entries(obj)) {
    console.log(key + ":" + value);
};

That’s all for today’s sharing~~

If there are any mistakes, welcome to correct them at any time.

Guess you like

Origin blog.csdn.net/weixin_55992854/article/details/120786639