(transfer) query and setting of object properties

Property Query

Object property query can be done through dot (.) or bracket ([]) operators. For the dot (.), the right side must be an identifier named after the property name (note: identifiers in the JavaScript language have their own legal rules and are different from quoted strings); for square brackets ([] ), the square brackets must be a string expression (of course, a string variable can also be used, and other values ​​that can be converted into strings, such as numbers, can also be dropped), and this string is the name of the attribute.

Let's look at a simple example:

var objPerson = {
    'name': 'Desert',
    'age': 35,
    'blog': 'w3cplus'
}
var name = objPerson.name,
    age = objPerson.age,
    blog = objPerson. blog;

console.log(name + 'already' + age + ' old, his Blog is: ' + blog);// Da Mo is 35 years old, his Blog is: w3cplus
also mentioned above, except for using The . operator can find out the property value of the object, and you can also use the [] operator to query the object property:

var objPerson = {
    'name': 'Desert',
    'age': 35,
    'blog': 'w3cplus'


    age = objPerson['age'],
    blog = objPerson['blog'];

console.log(name + 'already' + age + ', his Blog is: ' + blog);// Da Mo is 35 years old Now, his Blog is: When w3cplus
queries object properties, if there are spaces, connection characters, or reserved words in JavaScript in the property name, you need to use the [] operator to query. For example ,

var book ={
    "main title":"javascript", //There is a space in the attribute name, it must be represented by a string
    'sub-title':"the defintive guide", //There is a connection character in the attribute, so you need to use Double quotes
    "for":"all adiences", //"for is a reserved word, so double quotes are required.
    author:{ //The value of this property is an object
        firstName:"dabid", //The value of this property is also a Object
        surname:"flangan" //There are no quotation marks in the attribute names here
    }
};
var oName = oAuthor.surname //Get the attribute of author's "surname"
var oTitle =book["


The setting of properties is similar to the property query mentioned above. You can set the properties of the object through the . and [] operators. For example:

var obj = {}; //Create an empty object
obj.name = 'Damo';
obj['age'] = 35;
console.log(obj); // {name: "Damo", age: 35}
At this time, obj becomes:

obj = {
    name: "Da desert",
    age: 35
}
The above is an empty object created. If you want to modify an attribute value of an existing object, you can also use The same method:

var objPerson = {
    'name': 'Desert',
    'age': 53,
    'blog': 'w3cpus'
}

objPerson.age = 35;
objPerson['blog'] = 'w3cplus';
this time the object becomes:

objPerson = {
    'name': 'Desert',
    'age': 35,
    'blog': 'w3cplus'

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327059259&siteId=291194637