JavaScript Basics: Difference between revisions
Jump to navigation
Jump to search
| Line 18: | Line 18: | ||
Arrays are special objects. | Arrays are special objects. | ||
<pre> | <pre> | ||
var my_array = []; | var my_array = []; // make a new empty array | ||
var my_array = [1, 4, 2]; | |||
my_array.forEach( function(element){ | |||
// do something with element | |||
} | |||
</pre> | </pre> | ||
Revision as of 17:17, 18 April 2015
Link to external Javscript file
<head>
<title>Test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script src="spectra.js" type="text/javascript" ></script>
</head>
Types
The built-in types are string, number, boolean, null, undefined, object.
Use typeof some_var to get the type.
The following are considered false: false, 0, "", null, undefined, NaN.
Arrays
Arrays are special objects.
var my_array = []; // make a new empty array
var my_array = [1, 4, 2];
my_array.forEach( function(element){
// do something with element
}
Strings
" Hello ".trim() // "Hello"
Objects
var new_object = {}; // make a new empty object
new_object.name = "Bill"; // create a property
new_object["name"] = "Bill"; // same thing
for (var key in my_object){ // iterate over an object
// do something with key
// value is my_object[key]
}
Constructors
function Fruit (theColor, theSweetness, theFruitName, theNativeToLand) {
this.color = theColor;
this.sweetness = theSweetness;
this.fruitName = theFruitName;
this.nativeToLand = theNativeToLand;
this.showName = function () {
console.log("This is a " + this.fruitName);
}
this.nativeTo = function () {
this.nativeToLand.forEach(function (eachCountry) {
console.log("Grown in:" + eachCountry);
});
}
}
var mango = new Fruit ("Yellow", 8, "Mango", ["South America", "Central America", "West Africa"]);
Prototypes
Every object has a prototype property. This can be used to add attributes or methods after the constructor has been defined:
Fruit.prototype.peeled = false;
Fruit.prototype.peel = function() {
this.peeled = true;
}
Counter.prototype = {
};