Home > Web Front-end > JS Tutorial > JavaScript object attribute inspection, addition, deletion, access operation examples_javascript skills

JavaScript object attribute inspection, addition, deletion, access operation examples_javascript skills

WBOY
Release: 2016-05-16 15:50:56
Original
970 people have browsed it

Check properties

var mouse = {
 "name": "betta",
 "age": 3,
 "varieties": "milaoshu"
}
 
mouse.hasOwnProperty("name"); // true
mouse.hasOwnProperty("sex"); //false
Copy after login

Add attributes

Define an object dog, then assign various attributes, then assign the color attribute, and finally traverse all attributes and values

var dog={
 name:"芒果",
 type:"会之王",
 eat:function(){
  alert("吃");
 }
}
 Object.prototype.color="白色";
 var name;
 for(name in dog){
  document.write(name+" "+dog[name]+"<br>")
 }
Copy after login

The effect is as follows

name 芒果
type 会之王
eat function (){ alert("吃"); }
color 白色
Copy after login

Delete attribute

var cat = {
  "name": "tom",
  "sex": "man",
  "color": "yellow"
}
delete cat.name;
cat.sex = undefined;
cat.color = null;
alert("name属性是否存在:" + cat.hasOwnProperty("name")); //false
alert("sex属性是否存在:" + cat.hasOwnProperty("sex")); //true
alert("color属性是否存在:" + cat.hasOwnProperty("color")); //true
Copy after login

Access properties

var cat = {
  "name": "tom",
  "sex": "man",
  "color": "yellow"
}
var name1 = cat.name; //通过点操作符来访问对象属性
var name2 = cat["name"]; //通过中括号操作符来访问对象属性
Copy after login

There are two ways to create objects

var obj = new Object();
obj.name = "MangGuo";
obj.age = 25;

var obj = {
  name : "MangGuo", //name是属性名,"MangGuo"是值
  age : 25
}

Copy after login
source:php.cn
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