ECMAScript 2009, også kendt som ES5, var den første større revision af JavaScript.
Dette kapitel beskriver de vigtigste funktioner i ES5.
"brug strengt"
Adgang til streng[nummer]
Multiline strenge
String.trim()
Array.isArray()
Array forEach()
Matrixkort()
Array filter()
Array reduce()
Array reduceRight()
Array hver()
Array nogle()
Array indexOf()
Array lastIndexOf()
JSON.parse()
JSON.stringify()
Dato.nu()
Dato til ISOString()
Dato til JSON()
Ejendom getters og seters
Reserverede ord som egenskabsnavne
Objekt metoder
Object defineProperty()
Funktion bind()
Efterfølgende kommaer
ES5
er fuldt understøttet i alle moderne browsere:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9.0 | Yes | Yes | Yes | Yes |
"use strict"
definerer, at JavaScript-koden skal udføres i "strict mode".
Med strict mode kan du f.eks. ikke bruge udeklarerede variable.
Du kan bruge streng tilstand i alle dine programmer. Det hjælper dig med at skrive renere kode, som at forhindre dig i at bruge ikke-erklærede variabler.
"use strict"
er kun et strengudtryk. Gamle browsere vil ikke give en fejl, hvis de ikke forstår det.
Læs mere i JS Strict Mode.
Metoden charAt()
returnerer tegnet ved en specificeret indeks (position) i en streng:
var str = "HELLO WORLD";
str.charAt(0); // returns H
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>The charAt() method returns the character at a given position in a string:</p>
<p id="demo"></p>
<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str.charAt(0);
</script>
</body>
</html>
ES5 tillader ejendomsadgang på strenge:
var str = "HELLO WORLD";
str[0]; // returns H
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String Methods</h2>
<p>ECMAScript 5 allows property acces on strings:</p>
<p id="demo"></p>
<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str[0];
</script>
</body>
</html>
Ejendomsadgang på streng kan være lidt uforudsigelig.
Læs mere i JS String Methods.
"Hello \
Dolly!";
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>
You can break a code line within a text string with a backslash.
</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
</script>
</body>
</html>
\-metoden har muligvis ikke universel understøttelse.
Ældre browsere behandler muligvis mellemrummene omkring omvendt skråstreg anderledes.
Nogle ældre browsere gør tillad ikke mellemrum bag tegnet \.
En mere sikker måde at bryde en streng op er at bruge streng tilføjelse:
"Hello " +
"Dolly!";
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>The safest way to break a code line in a string is using string addition.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
</script>
</body>
</html>
ES5 tillader reserverede ord som egenskabsnavne:
var obj = {name: "John", new: "yes"}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>ECMAScript 5</h1>
<p>ECMAScript 5 allows reserved words as property names.</p>
<p id="demo"></p>
<script>
var obj = {name: "John", new: "yes"};
document.getElementById("demo").innerHTML = obj.new;
</script>
</body>
</html>
trim()
Metoden trim()
fjerner mellemrum fra begge sider af en streng.
var str = " Hello World! ";
alert(str.trim());
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trim() Method</h2>
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trim();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
</body>
</html>
Læs mere i JS String Methods.
Array.isArray()
Metoden isArray()
kontrollerer, om et objekt er et array.
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(fruits);
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The isArray() Method</h2>
<p>Click the button to check if "fruits" is an array.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x = document.getElementById("demo");
x.innerHTML = Array.isArray(fruits);
}
</script>
</body>
</html>
Læs mere i JS Arrays.
forEach()
Metoden forEach()
kalder en funktion én gang for hvert array-element.
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
function myFunction(value) {
txt = txt + value + "<br>";
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.forEach()</h2>
<p>Calls a function once for each array element.</p>
<p id="demo"></p>
<script>
var txt = "";
var numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value) {
txt = txt + value + "<br>";
}
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
map()
Dette eksempel multiplicerer hver matrixværdi med 2:
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
function myFunction(value) {
return value * 2;
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.map()</h2>
<p>Creates a new array by performing a function on each array element.</p>
<p id="demo"></p>
<script>
var numbers1 = [45, 4, 9, 16, 25];
var numbers2 = numbers1.map(myFunction);
document.getElementById("demo").innerHTML = numbers2;
function myFunction(value, index, array) {
return value * 2;
}
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
filter()
Dette eksempel opretter en ny matrix fra elementer med en værdi større end 18:
var numbers = [45, 4, 9, 16, 25];
var over18 =
numbers.filter(myFunction);
function myFunction(value) {
return value > 18;
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.filter()</h2>
<p>Creates a new array with all array elements that passes a test.</p>
<p id="demo"></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var over18 = numbers.filter(myFunction);
document.getElementById("demo").innerHTML = over18;
function myFunction(value, index, array) {
return value > 18;
}
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
reduce()
Dette eksempel finder summen af alle tal i en matrix:
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduce(myFunction);
function myFunction(total, value) {
return total + value;
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.reduce()</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id="demo"></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduce(myFunction);
document.getElementById("demo").innerHTML = "The sum is " + sum;
function myFunction(total, value, index, array) {
return total + value;
}
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
reduceRight()
Dette eksempel finder også summen af alle tal i en matrix:
var numbers1 = [45, 4, 9, 16, 25];
var sum = numbers1.reduceRight(myFunction);
function myFunction(total, value) {
return total + value;
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.reduceRight()</h2>
<p>This example finds the sum of all numbers in an array:</p>
<p id="demo"></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var sum = numbers.reduceRight(myFunction);
document.getElementById("demo").innerHTML = "The sum is " + sum;
function myFunction(total, value) {
return total + value;
}
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
every()
Dette eksempel kontrollerer, om alle værdier er over 18:
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.every(myFunction);
function myFunction(value) {
return
value > 18;
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.every()</h2>
<p>The every() method checks if all array values pass a test.</p>
<p id="demo"></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.every(myFunction);
document.getElementById("demo").innerHTML = "All over 18 is " + allOver18;
function myFunction(value, index, array) {
return value > 18;
}
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
some()
Dette eksempel kontrollerer, om nogle værdier er over 18:
var numbers = [45, 4, 9, 16, 25];
var allOver18 =
numbers.some(myFunction);
function myFunction(value) {
return
value > 18;
}
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array.some()</h2>
<p>The some() method checks if some array values pass a test.</p>
<p id="demo"></p>
<script>
var numbers = [45, 4, 9, 16, 25];
var allOver18 = numbers.some(myFunction);
document.getElementById("demo").innerHTML = "Some over 18 is " + allOver18;
function myFunction(value) {
return value > 18;
}
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
indexOf()
Søg i et array efter en elementværdi og returnerer dets position.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.indexOf("Apple");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The indexOf() Method</h2>
<p id="demo"></p>
<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
lastIndexOf()
lastIndexOf()
er det samme som indexOf()
, men søger fra slutningen af arrayet.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The lastIndexOf() Method</h2>
<p id="demo"></p>
<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;
document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>
</body>
</html>
Lær mere i JS Array Iteration Methods.
JSON.parse()
En almindelig brug af JSON er at modtage data fra en webserver.
Forestil dig, at du har modtaget denne tekststreng fra en webserver:
'{"name":"John", "age":30, "city":"New York"}'
JavaScript-funktionen JSON.parse()
bruges til at konvertere teksten til et JavaScript-objekt:
var obj = JSON.parse('{"name":"John", "age":30, "city":"New
York"}');
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>Creating an Object from a JSON String</h2>
<p id="demo"></p>
<script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</body>
</html>
Læs mere i vores JSON-tutorial.
JSON.stringify()
En almindelig brug af JSON er at sende data til en webserver.
Når data sendes til en webserver, skal dataene være en snor.
Forestil dig, at vi har dette objekt i JavaScript:
var obj = {name:"John", age:30, city:"New York"};
Brug JavaScript-funktionen JSON.stringify()
til at konvertere den til en streng.
var myJSON = JSON.stringify(obj);
Resultatet vil være en streng efter JSON-notationen.
myJSON er nu en streng og klar til at blive sendt til en server:
var obj = {name:"John", age:30, city:"New York"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>Create a JSON string from a JavaScript object.</h2>
<p id="demo"></p>
<script>
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>
</body>
</html>
Læs mere i vores JSON-tutorial.
Date.now()
Date.now()
returnerer antallet af millisekunder siden nul dato (1. januar. 1970 00:00:00 UTC).
var timInMSs = Date.now();
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Date.now()</h2>
<p>Date.now() is new in ECMAScript 5 (2009):</p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
document.getElementById("demo1").innerHTML = Date.now();
var d = new Date();
document.getElementById("demo2").innerHTML = d.getTime();
</script>
</body>
</html>
Date.now()
returnerer det samme som getTime() udført på et Date
-objekt.
Få mere at vide i JS Dates.
toISOString()
Metoden toISOString()
konverterer et Date-objekt til en streng ved hjælp af ISO-standardformatet:
const d = new Date();
document.getElementById("demo").innerHTML = d.toISOString();
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The toISOString() Method</h2>
<p>Convert a date to a string using the ISO standard:</p>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toISOString();
</script>
</body>
</html>
toJSON()
toJSON()
konverterer et Date-objekt til en streng, formateret som en JSON-dato.
JSON-datoer har samme format som ISO-8601-standarden: ÅÅÅÅ-MM-DDTHH:mm:ss.sssZ:
d = new Date();
document.getElementById("demo").innerHTML = d.toJSON();
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Date.toJSON()</h2>
<p id="demo"></p>
<script>
d = new Date();
document.getElementById("demo").innerHTML = d.toJSON();
</script>
</body>
</html>
ES5 giver dig mulighed for at definere objektmetoder med en syntaks, der ligner at hente eller indstille en ejendom.
Dette eksempel opretter en getter for en egenskab kaldet fullName:
// Create an object:
var person = {
firstName:
"John",
lastName : "Doe",
get
fullName() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the
object using a getter:
document.getElementById("demo").innerHTML =
person.fullName;
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Getters and Setters</h2>
<p>Getters and setters allow you to get and set properties via methods.</p>
<p>This example creates a getter for a property called fullName.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.fullName;
</script>
</body>
</html>
Dette eksempel opretter en sætter og en getter for sprogegenskaben:
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
get lang() {
return this.language;
},
set lang(value) {
this.language = value;
}
};
// Set an object
property using a setter:
person.lang = "en";
// Display data from the
object using a getter:
document.getElementById("demo").innerHTML =
person.lang;
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Getters and Setters</h2>
<p>Getters and setters allow you to get and set properties via methods.</p>
<p>This example creates a setter and a getter for the language property.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
get lang() {
return this.language;
},
set lang(value) {
this.language = value;
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
</script>
</body>
</html>
Dette eksempel bruger en sætter til at sikre opdateringer af store bogstaver af sprog:
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
set lang(value) {
this.language = value.toUpperCase();
}
};
// Set an object
property using a setter:
person.lang = "en";
// Display data from the
object:
document.getElementById("demo").innerHTML =
person.language;
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Getters and Setters</h2>
<p>Getters and setters allow you to get and set properties via methods.</p>
<p>This example has a modified setter to secure upper case uppdates of language.</p>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "",
set lang(value) {
this.language = value.toUpperCase();
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
</script>
</body>
</html>
Lær mere om Gettes og Setters i JS Object Accessors
Object.defineProperty()
Object.defineProperty()
er en ny Object-metode i ES5.
Det lader dig definere en objektegenskab og/eller ændre en egenskabs værdi og/eller metadata.
// Create an Object:
var person = {
firstName:
"John",
lastName : "Doe",
language : "NO",
};
// Change a Property:
Object.defineProperty(person, "language", {
value: "EN",
writable : true,
enumerable : true,
configurable : true
});
//
Enumerate Properties
var txt = "";
for (var x in person) {
txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML =
txt;
Prøv det selv →
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=iso-8859-2" http-equiv="Content-Type">
</head>
<body>
<h2>JavaScript defineProperty()</h2>
<p id="demo"></p>
<script>
// Create an Object:
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
};
// Change a Property:
Object.defineProperty(person, "language", {
value: "EN",
writable : true,
enumerable : true,
configurable : true
});
// Enumerate Properties
txt = "";
for (var x in person) {
txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Næste eksempel er den samme kode, bortset fra at den skjuler sprogegenskaben fra opregning:
// Create an Object:
var person = {
firstName:
"John",
lastName : "Doe",
language : "NO",
};
// Change a Property:
Object.defineProperty(person, "language", {
value: "EN",
writable : true,
enumerable : false,
configurable : true
});
//
Enumerate Properties
var txt = "";
for (var x in person) {
txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML =
txt;
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript defineProperty()</h2>
<p id="demo"></p>
<script>
// Create an Object:
var person = {
firstName: "John",
lastName : "Doe",
language : "NO",
};
// Change a Property:
Object.defineProperty(person, "language", {
value: "EN",
writable : true,
enumerable : false,
configurable : true
});
// Enumerate Properties
txt = "";
for (var x in person) {
txt += person[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Dette eksempel opretter en setter og en getter for at sikre opdateringer af store bogstaver af sprog:
// Create an Object:
var person = {
firstName: "John",
lastName :
"Doe",
language : "NO"
};
// Change a Property:
Object.defineProperty(person, "language", {
get : function() { return
language },
set : function(value) { language = value.toUpperCase()}
});
// Change Language
person.language = "en";
// Display Language
document.getElementById("demo").innerHTML = person.language;
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript defineProperty()</h2>
<p id="demo"></p>
<script>
// Create an Object:
var person = {
firstName: "John",
lastName : "Doe",
language : "NO"
};
// Change a Property:
Object.defineProperty(person, "language", {
get : function() { return language },
set : function(value) { language = value.toUpperCase()}
});
// Change language
person.language = "en";
// Display language
document.getElementById("demo").innerHTML = person.language;
</script>
</body>
</html>
ES5 tilføjede en masse nye objektmetoder til JavaScript:
// Create object with an existing object as prototype
Object.create(parent, donor)
// Adding or changing an object property
Object.defineProperty(object, property, descriptor)
// Adding or changing object properties
Object.defineProperties(object, descriptors)
// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)
// Returns all properties as an array
Object.getOwnPropertyNames(object)
// Accessing the prototype
Object.getPrototypeOf(object)
// Returns enumerable properties as an array
Object.keys(object)
// Prevents adding properties to an object
Object.preventExtensions(object)
// Returns true if properties can be added to an object
Object.isExtensible(object)
// Prevents changes of object properties (not values)
Object.seal(object)
// Returns true if object is sealed
Object.isSealed(object)
// Prevents any changes to an object
Object.freeze(object)
// Returns true if object is frozen
Object.isFrozen(object)
Lær mere i Object ECMAScript5.
Bind()
Med bind()
metoden kan et objekt låne en metode fra et andet objekt.
Dette eksempel opretter 2 objekter (person og medlem).
Medlemsobjektet låner fuldnavnsmetoden fra personobjektet:
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);
Prøv det selv →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Function bind()</h1>
<p>This example creates 2 objects (person and member).</p>
<p>The member object borrows the fullname method from person:</p>
<p id="demo"></p>
<script>
const person = {
firstName:"John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);
document.getElementById("demo").innerHTML = fullName();
</script>
</body>
</html>
Lær mere i Funktion bind().
ES5 tillader efterfølgende kommaer i objekt- og arraydefinitioner:
person = {
firstName: "John",
lastName: "
Doe",
age: 46,
}
points = [
1,
5,
10,
25,
40,
100,
];
ADVARSEL!!!
JSON tillader ikke efterfølgende kommaer.
//
Allowed:
var person = '{"firstName":"John", "lastName":"Doe",
"age":46}'
JSON.parse(person)
// Not allowed:
var person = '{"firstName":"John",
"lastName":"Doe", "age":46,}'
JSON.parse(person)
//
Allowed:
points = [40, 100, 1, 5, 25, 10]
// Not allowed:
points =
[40, 100, 1, 5, 25, 10,]