Object Review in JavaScript

上一篇 / 下一篇  2015-08-13 16:32:03 / 个人分类:JavaScript

Who's in Your Bracket?

And finally, let's go over retrieving property values. Throughout this section, we've been using dot notation to get the value of an object's property:

someObj.propName;

However, remember that we can also use bracket notation:

someObj["propName"];

An advantage of bracket notation is that we are not restricted to just using strings in the brackets. We can also use variables whose values are property names:

varsomeObj = {propName: someValue};varmyProperty ="propName";
someObj[myProperty];

The last line is exactly the sameas using someObj["propName"];.

Sample Codes:

var james = {

    job: "programmer",

    married: false

};


// set to the first property name of "james"

var aProperty = "job";

//var aProperty = james.job;

// print the value of the first property of "james" 

// using the variable "aProperty"

//console.log(aProperty);

console.log(james.married);

console.log(james.job);

console.log(james["job"]);

console.log(james[aProperty]);

++++++++++++++++++++++++

result:

falseprogrammerprogrammerprogrammer




TAG: Object object

wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-13 20:12:53
// to list all properties value

var nyc = {
    fullName: "New York City",
    mayor: "Bill de Blasio",
    population: 8000000,
    boroughs: 5
};

// write a for-in loop to print the value of nyc's properties

for ( var x in nyc ) {
    console.log(nyc[x]);
}
wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-13 19:17:43
I.D., Please
Alright! Let's get our hands dirty and start exploring some really cool stuff about objects in JavaScript. But before we can do that, how can we even tell if something is an object (as opposed to, say, a number or string)? It would be great if we could tell what type something is in JavaScript. Good thing there's a handy built-in operator to do this!

Say we have a variable thing and we don't know what type thing is. We can call typeof thing to figure this out. Generally, the most useful types are "number," "string," "function," and of course, "object."

As an example, the following example will print "object":

sample code:
---------------------------
// complete these definitions so that they will have
// the appropriate types
var anObj = { job: "I'm an object!" };
var aNumber = 42;
var aString = "I'm a string!";

console.log( typeof anObj ); // should print "object"
console.log( typeof aNumber ); // should print "number"
console.log( typeof aString ); // should print "string"
--------------------------

results below:
object
number
string
wilber.shinobi的个人空间 引用 删除 wilber.shinobi   /   2015-08-13 19:16:09
这bug,多明显,我就只是复制了一些东西,然后就遮住了页面,黑黑的一片什么鬼!
 

评分:0

我来说两句

Open Toolbar