SoFunction
Updated on 2025-02-28

Analysis of operation instances of detection and acquisition of JS object attributes

This article describes the detection and acquisition of JS object attributes. Share it for your reference, as follows:

1.1 in operator

In operator is used to check whether the object contains a certain property (note that the check is the key name, not the key value), and if included, it returns true, otherwise it returns false

var obj = { p: 1 }
'p' in obj // true
'toString' in obj // true

In the above code, there is a p attribute on the obj object, so when using the in operator, it gets true, but toString is not on the obj object, so why does it also return true? This is because the in operator cannot identify which attributes are the object itself and which are inherited. Because toString is a prototype object inherited from obj, it will return true.

1.2 for … in loop

for … in loop is used to traverse all properties of an object.

var obj = {a: 1, b: 2, c: 3};

for (var i in obj) {
 (obj[i]);
}

There are two points to note when using the loop

  1. It traverses all traversable properties of the object and skips non-traversable properties.
  2. It not only traverses the object's own properties, but also traverses inherited properties.

If you want to get your own properties, you need to combine the hasOwnProperty method to determine whether a property is the object's own property within the loop.

var person = { name: 'Lao Zhang' };

for (var key in person) {
 if ((key)) {
  (key);
 }
}

There are two other ways to get your own attributes:

es5:

Utilize (obj)

var person = { name: 'Lao Zhang' }
var props = (person) 

es6:

Utilize (obj)

var person = { name: 'Lao Zhang' }
var props = (person)

Interested friends can use itOnline HTML/CSS/JavaScript code running toolhttp://tools./code/HtmlJsRunTest the above code running effect.

For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript object-oriented tutorial》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.