In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the knowledge of "how to use JavaScript objects". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Introduction
In JavaScript, an object is a collection of key / value pairs. Values can contain properties and methods, and can contain all other JavaScript data types, such as strings, numbers, and Boolean values.
All objects in the JavaScript come from the constructor of the parent Object. Object provides us with many practical built-in methods that can be used directly in a single object. Unlike array prototype methods such as sort () and reverse () can only be used by array instances, object methods come directly from the Object constructor and use object instances as parameters. This is called a static method.
This tutorial introduces important built-in object methods, each of which covers specific methods and provides examples of usage.
Premise
To take full advantage of this tutorial, you should be familiar with creating, modifying, and working with objects, which you can view in the article "understanding objects in JavaScript."
For additional guidance on JavaScript, you can check out the "how to encode JavaScript" series.
Object.create ()
The Object.create () method is used to create a new object and link it to an existing object prototype.
We can create an instance of a job object and extend it to a more specific object.
/ / Initialize an object with properties and methods const job = {position: 'cashier', type:' hourly', isAvailable: true, showDetails () {const accepting = this.isAvailable? 'is accepting applications': "is not currently accepting applications"; console.log (`The ${this.position} position is ${this.type} and ${accepting}. `);}}; / / Use Object.create to pass properties const barista = Object.create (job); barista.position = "barista"; barista.showDetails (); Output The barista position is hourly and is accepting applications.
The barista object now has a position property-but all other properties and methods are available through the job prototype. Minimizing repetition through Object.create () is very effective in keeping the code DRY.
Object.keys ()
Object.keys () creates an array of object keys.
We can create an object and print an array of keys.
/ / Initialize an object const employees = {boss: 'Michael', secretary:' Pam', sales: 'Jim', accountant:' Oscar'}; / / Get the keys of the object const keys = Object.keys (employees); console.log (keys); Output ["boss", "secretary", "sales", "accountant"]
Object.keys () can also be used to iterate over the keys and values of an object.
/ / Iterate through the keys Object.keys (employees) .forEach (key = > {let value = employees [key]; console.log (`${key}: ${value}`); Output boss: Michael secretary: Pam sales: Jim accountant: Oscar
There is one difference between the enumerable properties returned by the for-in loop and Object.keys ():
The for-in loop also traverses the prototype properties
Object.keys () only returns its own (instance) properties
Object.keys () is also useful for checking the length of an object.
/ / Get the length of the keys const length = Object.keys (employees) .length; console.log (length); Output 4
Using this length attribute, we can calculate that the employees contains four own attributes.
Object.values ()
Object.values () creates an array containing the values of the object.
/ / Initialize an object const session = {id: 1, time: `26murJuly2018`, device: 'mobile', browser:' Chrome'}; / / Get all values of the object const values = Object.values (session); console.log (values); Output [1, "26-July-2018", "mobile", "Chrome"]
Object.keys () and Object.values () allow you to return data from an object.
Object.entries ()
Object.entries () creates a nested array of key / value pairs of objects.
/ / Initialize an object const operatingSystem = {name: 'Ubuntu', version: 18.04, license:' Open Source'}; / / Get the object key/value pairs const entries = Object.entries (operatingSystem); console.log (entries); Output [["name", "Ubuntu"] ["version", 18.04] ["license", "Open Source"]]
Once we have the key / value pair array, we can use the forEach () method to loop through and process the results.
/ / Loop through the results entries.forEach (entry = > {const [key, value] = entry; console.log (`$ {key}: ${value} `);}); Output name: Ubuntu version: 18.04license: Open Source
The Object.entries () method returns only the object instance's own properties, not any properties that can be inherited through its prototype.
Object.assign ()
Object.assign () is used to copy the value of one object to another.
We can create two objects and merge them using the Object.assign () method.
/ / Initialize an object const name = {firstName: 'Philip', lastName:' Fry'}; / / Initialize another object const details = {job: 'Delivery Boy', employer:' Planet Express'}; / / Merge the objects const character = Object.assign (name, details); console.log (character); Output {firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
You can also use the unfold syntax (Spread syntax) to accomplish the same task. In the following code, we will declare the character object by expanding the syntax to merge the name and details objects.
/ Initialize an object const name = {firstName: 'Philip', lastName:' Fry'}; / / Initialize another object const details = {job: 'Delivery Boy', employer:' Planet Express'}; / / Merge the object with the spread operator const character = {... name,... details} console.log (character); Output {firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
The unfold syntax (Spread syntax) also becomes a shallow clone (shallow-cloning) in the object syntax.
Object.freeze ()
Object.freeze () prevents the properties and values of an object from being modified, and prevents attributes from being added or removed from the object.
/ / Initialize an object const user = {username: 'AzureDiamond', password:' hunter2'}; / / Freeze the object const newUser = Object.freeze (user); newUser.password ='*'; newUser.active = true; console.log (newUser); Output {username: "AzureDiamond", password: "hunter2"}
In the above example, we tried to rewrite the password to overwrite hunter2 with *, but the value of password remains the same. We also tried to add a new attribute, active, but did not add it.
Object.isFrozen () can be used to determine whether the object is frozen and to return a Boolean value.
Object.seal ()
Object.seal () prevents new attributes from being added to the object, but allows existing properties to be modified. This method is similar to Object.freeze (). Refresh the console to avoid errors before implementing the following code.
/ / Initialize an object const user = {username: 'AzureDiamond', password:' hunter2'}; / / Seal the object const newUser = Object.seal (user); newUser.password ='*'; newUser.active = true; console.log (newUser); Output {username: "AzureDiamond", password: "*"}
The new active property was not added to the sealed object, but the password property was changed successfully.
Object.isSealed () can be used to determine whether the object is closed and return a Boolean value.
Object.getPrototypeOf ()
Object.getPrototypeOf () is used to obtain the internal concealment of the [[Prototype]] object, which can also be accessed through the _ _ proto__ property.
In this example, we can create an array that can access the Array prototype.
Const employees = ['Ron',' April', 'Andy',' Leslie']; Object.getPrototypeOf (employees); Output [constructor: stories, concat: bands, find: bands, findIndex: bands, pop: bands,...]
We can see the employees array accessing pop,find and other array prototype methods in the prototype output. We can prove this by testing the employees prototype, Array.prototype.
Object.getPrototypeOf (employees) = Array.prototype;Output true
This method can be used to get more information about an object or to ensure that it can access the prototype of another object.
There is also a related Object.setPrototypeOf () method that adds a prototype to another object. It is recommended that you use Object.create () because it is faster and has higher performance.
That's all for "how to use JavaScript objects". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 295
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.