JavaScript eksempler


Indholdsfortegnelse

    Vis indholdsfortegnelse


Hvad kan JavaScript?

JavaScript kan ændre HTML-indhold

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

</body>
</html>

JavaScript kan ændre HTML-attributter

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>

JavaScript kan ændre CSS-stil

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change the style of an HTML element.</p>

<button type="button" onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>

</body>
</html> 

JavaScript kan skjule HTML-elementer

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick="document.getElementById('demo').style.display='none'">Click Me!</button>

</body>
</html> 

JavaScript kan vise skjulte HTML-elementer

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can show hidden HTML elements.</p>

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

</body>
</html> 

Eksempler forklaret


Hvor skal JavaScript indsættes

JavaScript i <head>

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html> 

JavaScript i <body>

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html> 

JavaScript i en ekstern fil

<!DOCTYPE html>
<html>
<body>

<h2>Demo External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>This example links to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>

<script src="myScript.js"></script>

</body>
</html>

JavaScript i en ekstern url

<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Click Me</button>

<p>This example uses a full web URL to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>

<script src="https://www.w3schools.com/js/myScript.js"></script>

</body>
</html>

JavaScript i en ekstern mappe

<!DOCTYPE html>
<html>
<body>

<h2>External JavaScript</h2>

<p id="demo">A Paragraph.</p>

<button type="button" onclick="myFunction()">Try it</button>

<p>This example uses a file path to link to "myScript.js".</p>
<p>(myFunction is stored in "myScript.js")</p>

<script src="/js/myScript.js"></script>

</body>
</html>

Hvor skal forklares


JavaScript output

Skrivning i HTML-outputtet

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My first paragraph.</p>

<p>Never call document.write after the document has finished loading.
It will overwrite the whole document.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html> 

Skrivning ind i et HTML-element

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My First Paragraph.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html> 

Skriver ind i en vinduesadvarselsboks

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>
<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html> 

Skriver ind i browserkonsollen

<!DOCTYPE html>
<html>
<body>

<h2>Activate Debugging</h2>

<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>

<script>
console.log(5 + 6);
</script>

</body>
</html> 

Output forklaret


JavaScript syntaks

JavaScript-udsagn

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>

<p id="demo"></p>

<script>
var x, y, z;  // Declare 3 variables
x = 5;    // Assign the value 5 to x
y = 6;    // Assign the value 6 to y
z = x + y;  // Assign the sum of x and y to z

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";
</script>

</body>
</html>

JavaScript-numre

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Number can be written with or without decimals.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 10.50;
</script>

</body>
</html>

JavaScript-strenge

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Strings can be written with double or single quotes.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 'John Doe';
</script>

</body>
</html>

JavaScript-variabler

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a variable.
Then, x is assigned the value of 6:</p>

<p id="demo"></p>

<script>
let x;
x = 6;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript-operatører

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Operators</h2>

<p>JavaScript uses arithmetic operators to compute values (just like algebra).</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = (5 + 6) * 10;
</script>

</body>
</html>

JavaScript opgave

<!DOCTYPE html>
<html>
<body>

<h2>Assigning JavaScript Values</h2>

<p>In JavaScript the = operator is used to assign values to variables.</p>

<p id="demo"></p>

<script>
let x, y;
x = 5;
y = 6;
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

JavaScript-udtryk (ved hjælp af konstanter)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>

</body>
</html>

JavaScript-udtryk (ved hjælp af strenge)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "John" + " "  + "Doe";
</script>

</body>
</html>

JavaScript-udtryk (ved hjælp af variabler)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Expressions</h2>

<p>Expressions compute to values.</p>

<p id="demo"></p>

<script>
var x;
x = 5;
document.getElementById("demo").innerHTML = x * 10;
</script>

</body>
</html>

JavaScript søgeord

<!DOCTYPE html>
<html>
<body>

<h2>The var Keyword Creates Variables</h2>

<p id="demo"></p>

<script>
var x, y;
x = 5 + 6;
y = x * 10;
document.getElementById("demo").innerHTML = y;
</script>

</body>
</html>

JavaScript kommentarer

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments are NOT Executed</h2>

<p id="demo"></p>

<script>
let x;
x = 5;
// x = 6; I will not be executed
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JavaScript skelner mellem store og små bogstaver

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript is Case Sensitive</h2>

<p>Try to change lastName to lastname.</p>

<p id="demo"></p>

<script>
let lastname, lastName;
lastName = "Doe";
lastname = "Peterson";
document.getElementById("demo").innerHTML = lastName;
</script>

</body>
</html>

Syntaks forklaret



JavaScript-erklæringer

JavaScript-udsagn er kommandoer til browseren

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>In HTML, JavaScript statements are executed by the browser.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = "Hello Dolly.";
</script>

</body>
</html>

JavaScript-kode er en sekvens af udsagn

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>

<p id="demo"></p>

<script>
let x, y, z;  // Statement 1
x = 5;        // Statement 2
y = 6;        // Statement 3
z = x + y;    // Statement 4

document.getElementById("demo").innerHTML =
"The value of z is " + z + ".";  
</script>

</body>
</html>

JavaScript-udsagn er adskilt med semikolon

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript statements are separated by semicolons.</p>

<p id="demo1"></p>

<script>
let a, b, c;
a = 5;
b = 6;
c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>

Flere udsagn på én linje er tilladt

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>Multiple statements on one line are allowed.</p>

<p id="demo1"></p>

<script>
let a, b, c;
a = 5; b = 6; c = a + b;
document.getElementById("demo1").innerHTML = c;
</script>

</body>
</html>

JavaScript-udsagn kan grupperes sammen i kodeblokke

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>JavaScript code blocks are written between { and }</p>

<button type="button" onclick="myFunction()">Click Me!</button>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
function myFunction() {
  document.getElementById("demo1").innerHTML = "Hello Dolly!";
  document.getElementById("demo2").innerHTML = "How are you?";
}
</script>

</body>
</html>

Du kan bryde en kodelinje efter en operator eller et komma.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p>
The best place to break a code line is after an operator or a comma.
</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>

</body>
</html>

Udsagn forklaret


JavaScript kommentarer

Enkeltlinjekommentarer

<!DOCTYPE html>
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "JavaScript Comments";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

</body>
</html>

Enkeltlinjekommentarer i slutningen af en linje

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<p id="demo"></p>

<script>
let x = 5;      // Declare x, give it the value of 5
let y = x + 2;  // Declare y, give it the value of x + 2 

// Write y to demo:
document.getElementById("demo").innerHTML = y;
</script>


</body>
</html>

Kommentarer med flere linjer

<!DOCTYPE html>
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

</body>
</html>

Enkeltlinjekommentar for at forhindre udførelse

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>

<p>The line starting with // is not executed.</p>

</body>
</html>

Flere linjer kommenterer for at forhindre udførelse

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Comments</h2>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>
/*
document.getElementById("myH").innerHTML = "Welcome to my Homepage";
document.getElementById("myP").innerHTML = "This is my first paragraph.";
*/
document.getElementById("myP").innerHTML = "The comment-block is not executed.";
</script>


</body>
</html>

Kommentarer forklaret


JavaScript-variabler

JavaScript-variabler

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>


JavaScript-variabler som algebra

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>In this example, price1, price2, and total are variables.</p>

<p id="demo"></p>

<script>
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + total;
</script>

</body>
</html>


JavaScript-numre og strenge

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Strings are written with quotes.</p>
<p>Numbers are written without quotes.</p>

<p id="demo"></p>

<script>
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';

document.getElementById("demo").innerHTML =
pi + "<br>" + person + "<br>" + answer;
</script>

</body>
</html>


JavaScript var nøgleord.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>Create a variable, assign a value to it, and display it:</p>

<p id="demo"></p>

<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>

Erklære mange variable i én erklæring

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>You can declare many variables in one statement.</p>

<p id="demo"></p>

<script>
let person = "John Doe", carName = "Volvo", price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


Erklærer mange variabler multiline

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>You can declare many variables in one statement.</p>

<p id="demo"></p>

<script>
let person = "John Doe",
carName = "Volvo",
price = 200;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


En variabel uden en værdi returnerer værdien udefineret

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>A variable without a value has the value of:</p>
<p id="demo"></p>

<script>
let carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


Genangivelse af en variabel vil ikke ødelægge værdien

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>If you re-declare a JavaScript variable, it will not lose its value.</p>

<p id="demo"></p>

<script>
var carName = "Volvo";
var carName;
document.getElementById("demo").innerHTML = carName;
</script>

</body>
</html>


Tilføjelse af JavaScript-numre

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding 5 + 2 + 3 is:</p>
<p id="demo"></p>

<script>
let x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Tilføjelse af JavaScript-strenge

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding "John" + " " + "Doe" is:</p>
<p id="demo"></p>

<script>
let x = "John" + " " + "Doe";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Tilføjelse af strenge og tal

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Variables</h1>

<p>The result of adding "5" + 2 + 3 is:</p>
<p id="demo"></p>

<script>
let x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Variabler forklaret


JavaScript aritmetik

Tilføjelsesoperatoren (+).

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The + Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

Subtraktionsoperatoren (-).

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The - Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x - y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

Multiplikationsoperatoren (*)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

Divisionsoperatøren (/).

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The / Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x / y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

Modulus (%) operatoren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The % Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x % y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

Increment (++) operatoren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>In this example, y is incremented before it is assigned to x (pre-incremented).</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var y = 5;
var x = ++y;
document.getElementById("demo1").innerHTML = y;
document.getElementById("demo2").innerHTML = x;
</script>

</body>
</html>

Decrement (--) operatoren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>In this example, y is decremented before it is assigned to x (pre-decremented).</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
var y = 5;
var x = --y;
document.getElementById("demo1").innerHTML = y;
document.getElementById("demo2").innerHTML = x;
</script>

</body>
</html>

Aritmetik forklaret


JavaScript opgave

= tildelingsoperatøren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The = Operator</h2>

<p id="demo"></p>

<script>
let x = 10;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

+= tildelingsoperatoren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The += Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

-= tildelingsoperatøren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The -= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x -= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

*= tildelingsoperatoren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The *= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x *= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

/= tildelingsoperatøren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The /= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x /= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

%= tildelingsoperatoren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The %= Operator</h2>

<p id="demo"></p>

<script>
var x = 10;
x %= 5;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Opgave forklaret


Sammenkædning af JavaScript-strenge

Tilføjelse af to strenge ved hjælp af sammenkædningsoperatoren (+).

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>

<p>The + operator concatenates (adds) strings.</p>

<p id="demo"></p>

<script>
var txt1 = "What a very";
var txt2 = "nice day";
document.getElementById("demo").innerHTML = txt1 + txt2;
</script>

</body>
</html>

Tilføjelse af to strenge sammen med et mellemrum i den første streng

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Operators</h2>
<h2>The + Operator</h2>
<p>The + operator concatenates (adds) strings.</p>

<p id="demo"></p>

<script>
let text1 = "What a very ";
let text2 = "nice day";
document.getElementById("demo").innerHTML = text1 + text2;
</script>

</body>
</html>

Tilføjelse af to strenge med et mellemrum imellem

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>
<h2>The + operator</h2>
<p>The + operator concatenates (adds) strings.</p>

<p id="demo"></p>

<script>
var txt1 = "What a very";
var txt2 = "nice day";
document.getElementById("demo").innerHTML = txt1 + " " + txt2;
</script>

</body>
</html>

Tilføjelse af to strenge ved at bruge += operatoren

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>
<h2>The += Operator</h2>
<p>The assignment operator += can concatenate strings.</p>

<p id="demo"></p>

<script>
let text1 = "What a very ";
text1 += "nice day";
document.getElementById("demo").innerHTML = text1;
</script>

</body>
</html>

Tilføjelse af strenge og tal

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>
<h2>The + Operator</h2>
<p>Adding a number and a string, returns a string.</p>

<p id="demo"></p>

<script>
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
document.getElementById("demo").innerHTML =
x + "<br>" + y + "<br>" + z;
</script>

</body>
</html>

Sammenkædning forklaret


JavaScript-datatyper

Erklære (opret) strenge

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>

<p id="demo"></p>

<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" + 
answer2 + "<br>" + 
answer3;
</script>

</body>
</html>


Erklære (opret) tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numbers can be written with, or without decimals:</p>

<p id="demo"></p>

<script>
let x1 = 34.00;
let x2 = 34;
let x3 = 3.14;

document.getElementById("demo").innerHTML =
x1 + "<br>" + x2 + "<br>" + x3;
</script>

</body>
</html>


Erklære (opret) en matrix

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Array indexes are zero-based, which means the first item is [0].</p>

<p id="demo"></p>

<script>
const cars = ["Saab","Volvo","BMW"];

document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

Erklære (opret) et objekt

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
const person = {
  firstName : "John",
  lastName  : "Doe",
  age     : 50,
  eyeColor  : "blue"
};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Find typen af en variabel

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The typeof operator returns the type of a variable or an expression.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
typeof "" + "<br>" +
typeof "John" + "<br>" + 
typeof "John Doe" + "<br>" +
typeof 0 + "<br>" +
typeof 314 + "<br>" +
typeof 3.14 + "<br>" +
typeof (3.14);
</script>
</body>
</html>


Tilføjelse af to tal og en streng

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

<p id="demo"></p>

<script>
let x = 16 + 4 + "Volvo";
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>


Tilføjelse af en streng og to tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>JavaScript evaluates expressions from left to right. Different sequences can produce different results:</p>

<p id="demo"></p>

<script>
let x = "Volvo" + 16 + 4;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>


En udefineret variabel

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>
<p>The value (and the data type) of a variable with no value is <b>undefined</b>.</p>

<p id="demo"></p>

<script>
let car;
document.getElementById("demo").innerHTML =
car + "<br>" + typeof car;
</script>

</body>
</html> 

En tom variabel

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript</h2>

<p>An empty string has both a legal value and a type:</p>

<p id="demo"></p>

<script>
let car = "";
document.getElementById("demo").innerHTML =
"The value is: " +
car + "<br>" +
"The type is: " + typeof car;
</script>

</body>
</html>


Datatyper Forklaret


JavaScript objekter

Opret en JavaScript-variabel

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p id="demo"></p>

<script>
// Create and display a variable:
let car = "Fiat";
document.getElementById("demo").innerHTML = car;
</script>

</body>
</html>

Opret et JavaScript-objekt

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:
document.getElementById("demo").innerHTML = "The car type is " + car.type;
</script>

</body>
</html>

Opret et personobjekt (enkelt linje)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Opret et personobjekt (flere linjer)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Få adgang til objektegenskaber ved hjælp af .property

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     :  5566
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>

</body>
</html>


Få adgang til objektegenskaber ved hjælp af [egenskab]

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>There are two different ways to access an object property.</p>

<p>You can use person.property or person["property"].</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     :  5566
};

// Display some data from the object:
document.getElementById("demo").innerHTML =
person["firstName"] + " " + person["lastName"];
</script>

</body>
</html>


Få adgang til en funktionsegenskab som metode

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>An object method is a function definition, stored as a property value.</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();
</script>

</body>
</html>

Få adgang til en funktionsegenskab som en egenskab

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p>If you access an object method without (), it will return the function definition:</p>

<p id="demo"></p>

<script>
// Create an object:
const person = {
  firstName: "John",
  lastName : "Doe",
  id     : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName;
</script>

</body>
</html>

Objekter forklaret


JavaScript funktioner

En simpel funktion

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
</head>

<body>

<p>When you click "Try it", a function will be called.</p>
<p>The function will display a message.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

</body>
</html>

En funktion med et argument

<!DOCTYPE html>
<html>
<body>

<p>Click "Try it" to call a function with arguments</p>

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<p id="demo"></p>

<script>
function myFunction(name,job) {
  document.getElementById("demo").innerHTML = "Welcome " + name + ", the " + job + ".";
}
</script>

</body>
</html>

En funktion med et argument 2

<!DOCTYPE html>
<html> 
<head> 
<script> 
function myfunction(txt) { 
  document.getElementById("demo").innerHTML = txt
} 
</script> 
</head> 
<body> 

<p>When you click on one of the buttons, a function will be called. The function will display the argument that is passed to it.</p>

<form> 
  <input type="button" onclick="myfunction('Good Morning!')" value="In the Morning"> 
  <input type="button" onclick="myfunction('Good Evening!')" value="In the Evening"> 
</form> 

<p id="demo"></p>

</body> 
</html> 

En funktion, der returnerer en værdi

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>Call a function which performs a calculation and returns the result:</p>

<p id="demo"></p>

<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
  return a * b;
}
</script>

</body>
</html>

En funktion, der konverterer Fahrenheit til Celsius

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>Invoke (call) a function that converts from Fahrenheit to Celsius:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
  return (5/9) * (f-32);
}

let value = toCelsius(77);
document.getElementById("demo").innerHTML = value;
</script>

</body>
</html>

Et funktionskald uden()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>Accessing a function without () returns the function and not the function result:</p>
<p id="demo"></p>

<script>
function toCelsius(f) {
  return (5/9) * (f-32);
}

let value = toCelsius;
document.getElementById("demo").innerHTML = value;
</script>

</body>
</html>

Funktioner forklaret


JavaScript-begivenheder

En onclick-hændelse ændrer et HTML-element

<!DOCTYPE html>
<html>
<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>

<p id="demo"></p>

</body>
</html>

En onclick-hændelse ændrer sit eget element

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML Events</h2>
<button onclick="this.innerHTML=Date()">The time is?</button>

</body>
</html>

En onclick-hændelse kalder en funktion

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button>

<script>
function displayDate() {
  document.getElementById("demo").innerHTML = Date();
}
</script>

<p id="demo"></p>

</body>
</html> 

Begivenheder forklaret


JavaScript-strenge

Strenge kan skrives med enkelte eller dobbelte anførselstegn.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>

<p>Strings are written inside quotes.</p>
<p>You can use single or double quotes:</p>

<p id="demo"></p>

<script>
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';

document.getElementById("demo").innerHTML =
carName1 + " " + carName2; 
</script>

</body>
</html>


Vis nogle strengeksempler

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string:</p>

<p id="demo"></p>

<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" + 
answer2 + "<br>" + 
answer3;
</script>

</body>
</html>


Omvendt skråstreg før citater accepterer citater som citater.

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>

var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north.";

document.getElementById("demo").innerHTML = x + "<br>" + y; 

</script>

</body>
</html>


Find længden af en streng

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The length Property</h2>

<p>The length of the string is:</p>
<p id="demo"></p>

<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>

</body>
</html>

Du kan bryde tekststrengen med en omvendt skråstreg.

<!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>

Du kan ikke bryde kode med en omvendt skråstreg.

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Statements</h2>

<p id="demo">You cannot break a code line with a \ backslash.</p>

<script>
document.getElementById("demo").innerHTML = \
"Hello Dolly.";
</script>

</body>
</html>

Erstat tegn i en streng - replace()

<!DOCTYPE html>
<html>

<body>

<h1>JavaScript String Methods</h1>
<p>Replace &quot;Microsoft&quot; with &quot;W3Schools&quot; in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace("Microsoft","W3Schools");
}
</script>

</body>
</html>


Konverter streng til store bogstaver - toUpperCase()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Convert string to upper case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toUpperCase();
}
</script>

</body>
</html>

Konverter streng til små bogstaver - toLowerCase()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Convert string to lower case:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Hello World!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.toLowerCase();
}
</script>

</body>
</html>

Opdel en streng i en matrix - split()

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Methods</h1>
<p>Display the first array element, after a string split:</p>

<p id="demo"></p>

<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];
</script>

</body>
</html>


Streng forklaret


JavaScript-numre

Tal kan skrives med eller uden decimaler

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numbers can be written with or without decimals:</p>

<p id="demo"></p>

<script>
let x = 3.14;
let y = 3;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>

Ekstra store eller ekstra små tal kan skrives med eksponentnotation

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Extra large or extra small numbers can be written with scientific (exponent) notation:</p>

<p id="demo"></p>

<script>
let x = 123e5;
let y = 123e-5;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>

Nummer anses kun for nøjagtigt op til 15 cifre

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>Integer Precision</h2>

<p>Integers (numbers without a period or exponent notation) are accurate up to 15 digits:</p>

<p id="demo"></p>

<script>
let x = 999999999999999;
let y = 9999999999999999;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>


Flydende komma-regning er ikke altid 100 % nøjagtig

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>Floating Point Precision</h2>

<p>Floating point arithmetic is not always 100% accurate.</p>

<p id="demo"></p>

<script>
let x = 0.2 + 0.1;
document.getElementById("demo").innerHTML = "0.2 + 0.1 = " + x;
</script>

</body>
</html>


Men det hjælper at gange og dividere med 10

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Floating point arithmetic is not always 100% accurate:</p>
<p id="demo1"></p>

<p>But it helps to multiply and divide:</p>

<p id="demo2"></p>

<script>
let x = 0.2 + 0.1;
document.getElementById("demo1").innerHTML = "0.2 + 0.1 = " + x;
let y = (0.2*10 + 0.1*10) / 10;
document.getElementById("demo2").innerHTML = "0.2 + 0.1 = " + y;
</script>

</body>
</html>


Tilføjelse af to tal resulterer i et nyt tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you add two numbers, the result will be a number:</p>

<p id="demo"></p>

<script>
let x = 10;
let y = 20;
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>


Tilføjelse af to numeriske strenge resulterer i en sammenkædet streng

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you add two numeric strings, the result will be a concatenated string:</p>

<p id="demo"></p>

<script>
let x = "10";
let y = "20";
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>


Tilføjelse af et tal og en numerisk streng resulterer også i en sammenkædet streng

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you add a number and a numeric string, the result will be a concatenated string:</p>

<p id="demo"></p>

<script>
let x = 10;
let y = "20";
let z = x + y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>


Tilføjelse af en numerisk streng og et tal resulterer også i en sammenkædet streng

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you add a numeric string and a number, the result will be a concatenated string:</p>

<p id="demo"></p>

<script>
let x = "10";
let y = 20;
document.getElementById("demo").innerHTML = "The result is: " + x + y;
</script>

</body>
</html>


Almindelig fejl ved tilføjelse af strenge og tal 1

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A common mistake is to expect this result to be 30:</p>

<p id="demo"></p>

<script>
var x = 10;
var y = 20;
document.getElementById("demo").innerHTML =
"The result is: " + x + y;
</script>

</body>
</html>


Almindelig fejl ved tilføjelse af strenge og tal 2

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A common mistake is to expect this result to be 102030:</p>

<p id="demo"></p>

<script>
let x = 10;
let y = 20;
let z = "30";
let result = x + y + z;
document.getElementById("demo").innerHTML = result;
</script>

</body>
</html>


JavaScript vil forsøge at konvertere strenge til tal ved opdeling

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will try to convert strings to numbers when dividing:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x / y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript vil forsøge at konvertere strenge til tal ved multiplikation

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will try to convert strings to numbers when multiplying:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x * y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript vil forsøge at konvertere strenge til tal, når der trækkes fra

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will try to convert strings to numbers when subtracting:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x - y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript vil IKKE konvertere strenge til tal ved tilføjelse

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript will NOT convert strings to numbers when adding:</p>

<p id="demo"></p>

<script>
let x = "100";
let y = "10";
let z = x + y;   
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

Et tal divideret med en streng er NaN (ikke et tal)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A number divided by a non-numeric string becomes NaN (Not a Number):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "Apple";
</script>

</body>
</html>

Et tal divideret med en numerisk streng er et tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A number divided by a numeric string becomes a number:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "10";
</script>

</body>
</html>

Den globale JavaScript-funktion isNaN() returnerer, hvis en værdi er et tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>You can use the global JavaScript function isNaN() to find out if a value is not a number:</p>

<p id="demo"></p>

<script>
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = isNaN(x);
</script>

</body>
</html>

Brug af NaN i en matematisk operation vil altid returnere NaN

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you use NaN in a mathematical operation, the result will also be NaN:</p>

<p id="demo"></p>

<script>
let x = NaN;
let y = 5;
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

Brug af NaN i en matematisk strengoperation vil sammenkæde NaN

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>If you use NaN in a mathematical operation, the result can be a concatenation:</p>

<p id="demo"></p>

<script>
let x = NaN;
let y = "5";
document.getElementById("demo").innerHTML = x + y;
</script>

</body>
</html>

NaN (Ikke et tal) er et tal (Ja! typen af NaN returnerer tal)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>The typeof NaN is number:</p>

<p id="demo"></p>

<script>
let x = NaN;
document.getElementById("demo").innerHTML = typeof x;
</script>

</body>
</html>


Uendelighed returneres, hvis du beregner et tal uden for det størst mulige tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Infinity is returned if you calculate a number outside the largest possible number:</p>

<p id="demo"></p>

<script>
let myNumber = 2; 
let txt = "";
while (myNumber != Infinity) {
   myNumber = myNumber * myNumber;
   txt = txt + myNumber + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>


Division med nul genererer også Infinity

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Division by zero generates Infinity;</p>

<p id="demo"></p>

<script>
let x = 2/0;
let y = -2/0;
document.getElementById("demo").innerHTML = x + "<br>" + y;
</script>

</body>
</html>


Infinity er et tal (type Infinity returnerer tal)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Infinity is a number:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = typeof Infinity;
</script>

</body>
</html>


Konstanter, efterfulgt af 0x, fortolkes som hexadecimale

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numeric constants, preceded by 0x, are interpreted as hexadecimal:</p>

<p id="demo"></p>

<script>
let x = 0xFF;
document.getElementById("demo").innerHTML = "0xFF = " + x;
</script>

</body>
</html>


Metoden toString() kan udlæse tal som hex, oktal og binær

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>The toString() method can output numbers from base 2 to 36:</p>

<p id="demo"></p>

<script>
let myNumber = 32;
document.getElementById("demo").innerHTML =
"Decimal 32 = " + "<br><br>" + 

"Hexatrigesimal (base 36): " + myNumber.toString(36) + "<br>" +
"Duotrigesimal (base 32): " + myNumber.toString(32) + "<br>" +
"Hexadecimal (base 16): " + myNumber.toString(16) + "<br>" +
"Duodecimal (base 12): " + myNumber.toString(12) + "<br>" +
"Decimal (base 10): " + myNumber.toString(10) + "<br>" +
"Octal (base 8): " + myNumber.toString(8) + "<br>" +
"Binary (base 2): " + myNumber.toString(2);
</script>

</body>
</html>

Tal kan være objekter

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p id="demo"></p>

<script>
// x is a number
let x = 123;

// y is a Number object
let y = new Number(123);

document.getElementById("demo").innerHTML = typeof x + "<br>" + typeof y;
</script>

</body>
</html>

Tal og objekter kan ikke sikkert sammenlignes

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>Numbers and Number objects cannot be safely compared:</p>

<p id="demo"></p>

<script>
// x is a number
let x = 500;

// y is an object
let y = new Number(500);

document.getElementById("demo").innerHTML = (x===y);
</script>

</body>
</html>

Objekter og objekter kan ikke sikkert sammenlignes

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>JavaScript objects cannot be compared:</p>

<p id="demo"></p>

<script>
// x is an object
let x = new Number(500);

// y is an object
let y = new Number(500);

document.getElementById("demo").innerHTML = (x==y);
</script>

</body>
</html>

Tal forklaret


JavaScript-nummermetoder

Metoden toString() konverterer et tal til en streng

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>The toString() method can output numbers from base 2 to 36:</p>

<p id="demo"></p>

<script>
let myNumber = 32;
document.getElementById("demo").innerHTML =
"Decimal 32 = " + "<br><br>" + 

"Hexatrigesimal (base 36): " + myNumber.toString(36) + "<br>" +
"Duotrigesimal (base 32): " + myNumber.toString(32) + "<br>" +
"Hexadecimal (base 16): " + myNumber.toString(16) + "<br>" +
"Duodecimal (base 12): " + myNumber.toString(12) + "<br>" +
"Decimal (base 10): " + myNumber.toString(10) + "<br>" +
"Octal (base 8): " + myNumber.toString(8) + "<br>" +
"Binary (base 2): " + myNumber.toString(2);
</script>

</body>
</html>

Metoden valueOf() returnerer et tal som et tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The valueOf() method returns a number as a number:</p>

<p id="demo"></p>

<script>
let x = 123;

document.getElementById("demo").innerHTML = 
  x.valueOf() + "<br>" +
  (123).valueOf() + "<br>" +
  (100 + 23).valueOf();
</script>

</body>
</html>

toExponential() returnerer et tal med eksponentiel notation

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toExponential() method returns a string, with the number rounded and written using exponential notation.</p>

<p>An optional parameter defines the number of digits behind the decimal point.</p>

<p id="demo"></p>

<script>
let x = 9.656;
document.getElementById("demo").innerHTML =
  x.toExponential() + "<br>" + 
  x.toExponential(2) + "<br>" + 
  x.toExponential(4) + "<br>" + 
  x.toExponential(6);
</script>

</body>
</html>

Metoden toFixed() afrunder et tal til et antal cifre

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toFixed() method rounds a number to a given number of digits.</p>
<p>For working with money, toFixed(2) is perfect.</p>

<p id="demo"></p>

<script>
let x = 9.656;
document.getElementById("demo").innerHTML =
  x.toFixed(0) + "<br>" +
  x.toFixed(2) + "<br>" +
  x.toFixed(4) + "<br>" +
  x.toFixed(6);
</script>

</body>
</html>

toPrecision()-metoden et tal skrevet med en specificeret længde

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toPrecision() method returns a string, with a number written with a specified length:</p>

<p id="demo"></p>

<script>
let x = 9.656;
document.getElementById("demo").innerHTML = 
  x.toPrecision() + "<br>" +
  x.toPrecision(2) + "<br>" +
  x.toPrecision(4) + "<br>" +
  x.toPrecision(6);  
</script>

</body>
</html>

Den globale metode Number() konverterer variable til tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Methods</h2>

<p>The Number() method converts variables to numbers:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  Number(true) + "<br>" +
  Number(false) + "<br>" +
  Number("10") + "<br>" + 
  Number("  10") + "<br>" +
  Number("10  ") + "<br>" +
  Number(" 10  ") + "<br>" +
  Number("10.33") + "<br>" + 
  Number("10,33") + "<br>" +
  Number("10 33") + "<br>" +
  Number("John");
</script>

</body>
</html>


Den globale metode Number() kan endda konvertere datoer til tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Methods</h2>

<p>The Number() method can convert a date to a number:</p>

<p id="demo"></p>

<script>
let x = new Date("2017-09-30");
document.getElementById("demo").innerHTML = Number(x); 
</script>

</body>
</html>


Den globale metode parseInt() konverterer strenge til tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Functions</h2>
<h2>parseInt()</h2>
<p>The global JavaScript function parseInt() converts strings to numbers:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  parseInt("-10") + "<br>" +
  parseInt("-10.33") + "<br>" +
  parseInt("10") + "<br>" +
  parseInt("10.33") + "<br>" +
  parseInt("10 6") + "<br>" +  
  parseInt("10 years") + "<br>" +  
  parseInt("years 10");  
</script>

</body>
</html>


Den globale metode parseFloat() konverterer strenge til tal

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Global Methods</h2>

<p>The parseFloat() method converts strings to numbers:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  parseFloat("10") + "<br>" +
  parseFloat("10.33") + "<br>" +
  parseFloat("10 6") + "<br>" +  
  parseFloat("10 years") + "<br>" +
  parseFloat("years 10");    
</script>

</body>
</html>


MAX_VALUE returnerer det størst mulige tal i JavaScript

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The MAX_VALUE Property</h2>

<p>The largest possible number in JavaScript is:</p>
<p id="demo"></p>

<script>
let x = Number.MAX_VALUE;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

MIN_VALUE returnerer det mindst mulige tal i JavaScript

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The MIN_VALUE Property</h2>

<p>The smallest number possible in JavaScript is:</p>
<p id="demo"></p>

<script>
let x = Number.MIN_VALUE;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

POSITIVE_INFINITY repræsenterer uendeligt

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The POSITIVE_INFINITY Property</h2>

<p id="demo"></p>

<script>
let x = Number.POSITIVE_INFINITY;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

POSITIVE_INFINITY returneres ved overløb

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The POSITIVE_INFINITY Property</h2>

<p>POSITIVE_INFINITY is returned on overflow:</p>
<p id="demo"></p>

<script>
let x = 1 / 0;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

NEGATIVE_INFINITY repræsenterer negativ uendelighed

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The NEGATIVE_INFINITY Property</h2>

<p></p>

<p id="demo"></p>

<script>
let x = Number.NEGATIVE_INFINITY;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

NEGATIVE_INFINITY returneres ved overløb

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Numbers</h1>
<h2>The NEGATIVE_INFINITY Property</h2>

<p>NEGATIVE_INFINITY is returned on overflow:</p>
<p id="demo"></p>

<script>
let x = -1 / 0;
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

NaN repræsenterer "Not-a-Number"

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Properties</h2>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Number.NaN;
</script>

</body>
</html>

Aritmetik udført på en streng vil resultere i NaN

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Numbers</h2>

<p>A number divided by a non-numeric string becomes NaN (Not a Number):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 100 / "Apple";
</script>

</body>
</html>

Brug af en Number-egenskab på en variabel vil returnere udefineret

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Number Properties</h1>

<p>Using a Number property on a variable, or value, will return undefined:</p>

<p id="demo"></p>

<script>
let x = 6;
document.getElementById("demo").innerHTML = x.MAX_VALUE;
</script>

</body>
</html>

Talmetoder forklaret


JavaScript matematik

Math.PI returnerer værdien af PI

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.PI</h2>

<p>Math.PI returns the ratio of a circle's circumference to its diameter:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>

</body>
</html>

Math.round(x) returnerer den afrundede værdi af x

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.round()</h2>

<p>Math.round(x) returns the value of x rounded to its nearest integer:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.round(4.5);
</script>

</body>
</html>

Math.pow(x, y) returnerer værdien af x i potensen af y

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.pow()</h2>

<p>Math.pow(x,y) returns the value of x to the power of y:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>

</body>
</html>

Math.sqrt(x) returnerer kvadratroden af x

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.sqrt()</h2>

<p>Math.sqrt(x) returns the square root of x:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.sqrt(64);
</script>

</body>
</html>

Math.abs(x) returnerer den absolutte (positive) værdi af x

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.abs()</h2>

<p>Math.abs(x) returns the absolute (positive) value of x:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.abs(-4.7);
</script>

</body>
</html>

Math.ceil(x) returnerer værdien af x rundet op

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.ceil()</h2>

<p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.ceil(4.4);
</script>

</body>
</html>

Math.floor(x) returnerer værdien af x rundet ned

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.floor()</h2>

<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
</script>

</body>
</html>

Math.sin(x) returnerer sin af vinklen x (angivet i radianer)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.sin()</h2>

<p>Math.sin(x) returns the sin of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>

</body>
</html>

Math.cos(x) returnerer cosin for vinklen x (angivet i radianer)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.cos()</h2>

<p>Math.cos(x) returns the cosine of x (given in radians):</p>
<p>Angle in radians = (angle in degrees) * PI / 180.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"The cosine value of 0 degrees is " + Math.cos(0 * Math.PI / 180);
</script>

</body>
</html>

Math.max() returnerer tallet med den højeste værdi fra en liste over argumenter

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.max()</h2>

<p>Math.max() returns the highest value in a list of arguments.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.max(0, 150, 30, 20, -8, -200);
</script>

</body>
</html>

Math.min() for at returnere tallet med den laveste værdi fra en liste over argumenter

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.min()</h2>

<p>Math.min() returns the lowest value in a list of arguments:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.min(0, 150, 30, 20, -8, -200);
</script>

</body>
</html>

Konvertering af Celsius til Fahrenheit

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Celcius to Fahrenhet</h2>

<p>Insert a number into one of the input fields below:</p>

<p><input id="c" onkeyup="convert('C')"> degrees Celsius</p>

<p><input id="f" onkeyup="convert('F')"> degrees Fahrenheit</p> 

<p>Note that the <b>Math.round()</b> method is used, so that the result will be returned as an integer.</p>

<script>
function convert(degree) {
  var x;
  if (degree == "C") {
    x = document.getElementById("c").value * 9 / 5 + 32;
    document.getElementById("f").value = Math.round(x);
  } else {
    x = (document.getElementById("f").value -32) * 5 / 9;
    document.getElementById("c").value = Math.round(x);
  }
}
</script>

</body>
</html>

Matematik forklaret


JavaScript tilfældig

Math.random() returnerer et tilfældigt tal mellem 0 (inkluderet) og 1 (udelukket)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p>Math.random() returns a random number between 0 (included) and 1 (excluded):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Math.random();
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem 0 og 9 (begge inkluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 10) returns a random integer between 0 and 9 (both 
included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10);
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem 0 og 10 (begge inkluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 11) returns a random integer between 0 and 10 (both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 11);
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem 0 og 99 (begge inkluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 100)) returns a random integer between 0 and 99 
(both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100);
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem 0 og 100 (begge inkluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor() used with Math.random() * 101 returns a random integer between 0 and 100 
(both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 101);
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem 1 og 10 (begge inkluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 10) + 1) returns a random integer between 1 and 10 
(both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 10) + 1;
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem 1 og 100 (begge inkluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math</h2>

<p>Math.floor(Math.random() * 100) + 1) returns a random integer between 1 and 
100 (both included):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
Math.floor(Math.random() * 100) + 1;
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem x (inkluderet) og y (ekskluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 0 
and 9 (both included):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(0,10)">Click Me</button>

<p id="demo"></p>

<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}
</script>

</body>
</html>

Sådan returneres et tilfældigt heltal mellem x og y (begge inkluderet)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p>Every time you click the button, getRndInteger(min, max) returns a random number between 1 and 10 (both included):</p>

<button onclick="document.getElementById('demo').innerHTML = getRndInteger(1,10)">Click Me</button>

<p id="demo"></p>

<script>
function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1) ) + min;
}
</script>

</body>
</html>

Tilfældig forklaret


JavaScript-datoer

Brug Date() til at vise dagens dato og klokkeslæt

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>Using new Date()</h2>
<p>new Date() without arguments, creates a date object with the current date and time:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Brug getFullYear() til at vise året

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>The getFullYear() Method</h2>
<p>Return the full year of a date object:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getFullYear();
</script>

</body>
</html>

Brug getTime() til at beregne antallet af millisekunder siden 1970

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getTime() Method</h2>
<p></p>
<p>Return the number of milliseconds since midnight January 1, 1970:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getTime();
</script>

</body>
</html>

Brug setFullYear() til at indstille en bestemt dato

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript setFullYear()</h2>
<p>The setFullYear() method sets the year of a date object:</p>

<p id="demo"></p>

<script>
const d = new Date();
d.setFullYear(2020);
document.getElementById("demo").innerHTML = d;
</script>

</body>
</html>

Brug toUTCString() til at konvertere dagens dato (ifølge UTC) til en streng

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Dates</h1>
<h2>The toUTCString() Method</h2>
<p>Convert a date to a string using the UTC standard:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.toUTCString();
</script>

</body>
</html>

Brug getDay() til at vise ugedagen som et tal

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getDay() Method</h2>
<p>Return the weekday as a number:</p>

<p id="demo"></p>

<script>
const d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
</script>

</body>
</html>

Brug getDay() og en matrix til at vise ugedagen som et navn

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Dates</h1>
<h2>The getDay() Method</h2>
<p>Return the weekday as a number.</p>
<p>You can use an array of names to return the weekday as a name:</p>

<p id="demo"></p>

<script>
const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

const d = new Date();
let day = days[d.getDay()];
document.getElementById("demo").innerHTML = day;
</script>

</body>
</html>

Vis et ur

<!DOCTYPE html>
<html>

<body onload="startTime()">

<h2>JavaScript Clock</h2>

<div id="txt"></div>

<script>
function startTime() {
  const today = new Date();
  let h = today.getHours();
  let m = today.getMinutes();
  let s = today.getSeconds();
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('txt').innerHTML =  h + ":" + m + ":" + s;
  setTimeout(startTime, 1000);
}

function checkTime(i) {
  if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
  return i;
}
</script>

</body>
</html>

Datoer forklaret


JavaScript-arrays

Opret et array I

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Opret et array II

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = [
  "Saab",
  "Volvo",
  "BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Få adgang til et array-element

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>

<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

Skift et array-element

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Bracket Indexing</h2>

<p>Array elements are accessed using their index number:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits[0] = "Kiwi";
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Få adgang til et komplet array

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Find længden af et array

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The length Property</h2>

<p>The length property returns the length of an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
document.getElementById("demo").innerHTML = size;
</script>

</body>
</html>

Sløjfe gennem et array

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Looping an Array</h2>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";
for (let i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Tilføj et element til en matrix

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p>The length property provides an easy way to append new elements to an array without using the push() method.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
  fruits[fruits.length] = "Lemon";
  document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>

Tilføj udefinerede "huller" til et array

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p>Adding elements with high indexes can create undefined "holes" in an array.</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon";

let fLen = fruits.length;
let text = "";
for (i = 0; i < fLen; i++) {
  text += fruits[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Arrays forklaret


JavaScript-array-metoder

Tilføj et element til en matrix

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The push() Method</h2>

<p>The push() method appends a new element to an array:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.push("Kiwi");
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Fjern det sidste element i et array - pop()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The pop() Method</h2>

<p>The pop() method removes the last element from an array.</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.pop();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Sammenføj alle elementer i en matrix til en streng - join()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The join() Method</h2>

<p>The join() method joins array elements into a string.</p>
<p>It this example we have used " * " as a separator between the elements:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>

</body>
</html>

Forbind to arrays - concat()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The concat() Method</h2>

<p>The concat() method merges (concatenates) arrays:</p>

<p id="demo"></p>

<script>
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);

document.getElementById("demo").innerHTML = myChildren;
</script>

</body>
</html>

Forbind tre arrays - concat()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The concat() Method</h2>

<p>The concat() method merges (concatenates) arrays:</p>

<p id="demo"></p>

<script>
const array1 = ["Cecilie", "Lone"];
const array2 = ["Emil", "Tobias", "Linus"];
const array3 = ["Robin", "Morgan"];

const myChildren = array1.concat(array2, array3); 

document.getElementById("demo").innerHTML = myChildren;
</script>

</body>
</html>

Tilføj et element til position 2 i et array - splice()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The splice() Method</h2>

<p>The splice() method adds new elements to an array:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Konverter et array til en streng - toString()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1> 
<h2>The toString() Method</h2>

<p>The toString() method returns an array as a comma separated string:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>

</body>
</html>

Tilføj nye elementer til begyndelsen af et array - unshift()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1> 
<h2>The unshift() Method</h2>

<p>The unshift() method adds new elements to the beginning of an array:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.unshift("Lemon");
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Fjern det første element i et array - shift()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The shift() Method</h2>

<p>The shift() method removes the first element of an array (and "shifts" the other elements to the left):</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.shift();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Vælg elementer fra et array - slice()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The slice() Method</h2>

<p>When the slice() method is given two arguments, it selects array elements from the start argument, and up to (but not included) the end argument:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1,3);
document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus;
</script>

</body>
</html>

Array-metoder forklaret


JavaScript Array Sort

Sorter en matrix i stigende rækkefølge

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The sort() method sorts an array alphabetically:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

fruits.sort();
document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Sorter en matrix i faldende rækkefølge

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Sort in Reverse</h2>

<p>The reverse() method reverses the elements in an array.</p>
<p>By combining sort() and reverse() you can sort an array in descending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
// Create and display an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;

// First sort the array
fruits.sort();

// Then reverse it:
fruits.reverse();

document.getElementById("demo2").innerHTML = fruits;
</script>

</body>
</html>

Sorter en række af tal stigende

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort the array in ascending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;  

points.sort(function(a, b){return a - b});
document.getElementById("demo2").innerHTML = points;
</script>

</body>
</html>

Sorter en række faldende tal

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort the array in descending order:</p>

<p id="demo1"></p>
<p id="demo2"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;

points.sort(function(a, b){return b - a});
document.getElementById("demo2").innerHTML = points;
</script>

</body>
</html>

Sorter tal (alfabetisk eller numerisk)

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the buttons to sort the array alphabetically or numerically.</p>

<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction1() {
  points.sort();
  document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
  points.sort(function(a, b){return a - b});
  document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Sorter matrixnumre i tilfældig rækkefølge

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the button (again and again) to sort the array in random order.</p>

<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;  

function myFunction() {
  points.sort(function(){return 0.5 - Math.random()});
  document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Find det laveste tal i en matrix

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

Find det højeste tal i en matrix

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
document.getElementById("demo").innerHTML = points[0];
</script>

</body>
</html>

Find det laveste tal i en matrix ved hjælp af Math.min()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Array Sort</h1>

<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
  return Math.min.apply(null, arr);
}
</script>

</body>
</html>

Find det højeste tal i en matrix ved hjælp af Math.max()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Array Sort</h1>

<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
  return Math.max.apply(null, arr);
}
</script>

</body>
</html>

Brug af en "hjemmelavet" myArrayMin metode

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>
<p>The lowest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMin(points);

function myArrayMin(arr) {
  let len = arr.length;
  let min = Infinity;
  while (len--) {
    if (arr[len] < min) {
      min = arr[len];
    }
  }
  return min;
}
</script>

</body>
</html>

Brug af en "hjemmelavet" myArrayMax metode

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>
<p>The highest number is <span id="demo"></span>.</p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = myArrayMax(points);

function myArrayMax(arr) {
  let len = arr.length;
  let max = -Infinity;
  while (len--) {
    if (arr[len] > max) {
      max = arr[len];
    }
  }
  return max;
}
</script>

</body>
</html>

Sorter objekter efter numeriske egenskaber

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Sort car objects on age:</p>

<p id="demo"></p>

<script>
const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

displayCars();

cars.sort(function(a, b){return a.year - b.year});
displayCars();

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

</body>
</html>

Sorter objekter efter strengegenskaber

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the buttons to sort car objects on type.</p>

<button onclick="myFunction()">Sort</button>
<p id="demo"></p>

<script>
const cars = [
  {type:"Volvo", year:2016},
  {type:"Saab", year:2001},
  {type:"BMW", year:2010}
];

displayCars();

function myFunction() {
  cars.sort(function(a, b){
    let x = a.type.toLowerCase();
    let y = b.type.toLowerCase();
    if (x < y) {return -1;}
    if (x > y) {return 1;}
    return 0;
  });
  displayCars();
}

function displayCars() {
  document.getElementById("demo").innerHTML =
  cars[0].type + " " + cars[0].year + "<br>" +
  cars[1].type + " " + cars[1].year + "<br>" +
  cars[2].type + " " + cars[2].year;
}
</script>

</body>
</html>

Array Sort forklaret


JavaScript Array Iteration

Array.forEach()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The forEach() Method</h2>

<p>Call a function once for each array element:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];

let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;

function myFunction(value, index, array) {
  txt += value + "<br>"; 
}
</script>

</body>
</html>

Array.map()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The map() Method</h2>

<p>Create a new array by performing a function on each array element:</p>

<p id="demo"></p>

<script>
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

document.getElementById("demo").innerHTML = numbers2;

function myFunction(value, index, array) {
  return value * 2;
}
</script>

</body>
</html>

Array.filter()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The filter() Method</h2>

<p>Create a new array from all array elements that passes a test:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

document.getElementById("demo").innerHTML = over18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Array.reduce()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduce() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}
</script>

</body>
</html>

Array.reduceRight()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The reduceRight() Method</h2>

<p>Find the sum of all numbers in an array:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);

document.getElementById("demo").innerHTML = "The sum is " + sum;

function myFunction(total, value, index, array) {
  return total + value;
}
</script>

</body>
</html>

Array.every()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The every() Method</h2>

<p>The every() method checks if all array values pass a test.</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

document.getElementById("demo").innerHTML = "All over 18 is " + allOver18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Array.some()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The some() Method</h2>

<p>The some() method checks if some array values pass a test:</p>

<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);

document.getElementById("demo").innerHTML = "Some over 18 is " + someOver18;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Array.indexOf()

<!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>

Array.lastIndexOf()

<!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>

Array.find()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The find() Method</h2>

<p id="demo"></p>

<script>
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

document.getElementById("demo").innerHTML = "First number over 18 is " + first;

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Array.findIndex()

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The findIndex() Method</h2>

<p id="demo"></p>

<script>
const numbers = [4, 9, 16, 25, 29];

document.getElementById("demo").innerHTML = "First number over 18 has index " + numbers.findIndex(myFunction);

function myFunction(value, index, array) {
  return value > 18;
}
</script>

</body>
</html>

Array Iteration forklaret


JavaScript Type konvertering

Vis typen af alle variabeltyper

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The typeof Operator</h2>

<p>The typeof operator returns the type of a variable, object, function or expression:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
"'John' is " + typeof "John" + "<br>" +
"3.14 is " + typeof 3.14 + "<br>" +
"NaN is " + typeof NaN + "<br>" +
"false is " + typeof false + "<br>" +
"[1, 2, 3, 4] is " + typeof [1, 2, 3, 4] + "<br>" +
"{name:'John', age:34} is " + typeof {name:'John', age:34} + "<br>" +
"new Date() is " + typeof new Date() + "<br>" +
"function () {} is " + typeof function () {} + "<br>" +
"myCar is " + typeof myCar + "<br>" +
"null is " + typeof null;
</script>

</body>
</html>

Vis konstruktøren af alle variabeltyper

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Properties</h1>
<h2>The constructor Property</h2>

<p>The constructor property returns the constructor function for a variable or an 
object.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 
  "john".constructor + "<br>" +
  (3.14).constructor + "<br>" +
  false.constructor + "<br>" +
  [1,2,3,4].constructor + "<br>" +
  {name:'john', age:34}.constructor + "<br>" +
  new Date().constructor + "<br>" +
  function () {}.constructor;
</script>

</body>
</html>


Konverter et tal til en streng ved hjælp af String()

<!DOCTYPE html>
<html>
<body>

<h2>The JavaScript String() Method</h2>

<p>The String() method can convert a number to a string.</p>

<p id="demo"></p>

<script>
let x = 123;
document.getElementById("demo").innerHTML =
  String(x) + "<br>" +
  String(123) + "<br>" +
  String(100 + 23);
</script>
</body>
</html>

Konverter et tal til en streng ved hjælp af toString()

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toString() method converts a number to a string.</p>

<p id="demo"></p>

<script>
let x = 123;
document.getElementById("demo").innerHTML =
  x.toString() + "<br>" +
   (123).toString() + "<br>" +
   (100 + 23).toString();
</script>

</body>
</html>

Find ud af, om en variabel er en matrix

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p>This &quot;home made&quot; isArray() function returns true when used on an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Apple"];
document.getElementById("demo").innerHTML = isArray(fruits);

function isArray(myArray) {
  return myArray.constructor.toString().indexOf("Array") > -1;
}
</script>

</body>
</html>

Find ud af, om en variabel er en dato

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Date Object</h2>
<p>This "home made" isDate() function returns true when used on an date:</p>

<p id="demo"></p>

<script>
const myDate = new Date();
document.getElementById("demo").innerHTML = isDate(myDate);

function isDate(myDate) {
  return myDate.constructor.toString().indexOf("Date") > -1;
}
</script>

</body>
</html>

Typekonvertering forklaret


JavaScript Booleans

Vis værdien af Boolean (10 > 9)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the value of Boolean(10 &gt; 9):</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = Boolean(10 > 9);
</script>

</body>
</html>

Vis værdien 10 > 9

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the value of 10 &gt; 9:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 10 > 9;
</script>

</body>
</html>

Alt med en reel værdi er sandt

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"100 is " + Boolean(100) + "<br>" +
"3.14 is " + Boolean(3.14) + "<br>" +
"-15 is " + Boolean(-15) + "<br>" +
"Any (not empty) string is " + Boolean("Hello") + "<br>" +
"Even the string 'false' is " + Boolean('false') + "<br>" +
"Any expression (except zero) is " + Boolean(1 + 7 + 3.14);
</script>

</body>
</html>

Den boolske værdi af nul er falsk

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of 0:</p>

<p id="demo"></p>

<script>
let x = 0;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Den boolske værdi af minus nul er falsk

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of  -0:</p>

<p id="demo"></p>

<script>
let x = -0;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Den boolske værdi af en tom streng er falsk

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of "":</p>

<p id="demo"></p>

<script>
let x = "";
document.getElementById("demo").innerHTML = Boolean("");
</script>

</body>
</html>

Den boolske værdi af undefined er falsk

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of undefined:</p>

<p id="demo"></p>

<script>
let x;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Den boolske værdi af null er falsk

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of null:</p>

<p id="demo"></p>

<script>
let x = null;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Den boolske værdi af false er falsk

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of false:</p>

<p id="demo"></p>

<script>
let x = false;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Den boolske værdi af NaN er falsk

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Booleans</h1>
<p>Display the Boolean value of NaN:</p>

<p id="demo"></p>

<script>
let x = 10 / "Hello";
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Booleans forklaret


JavaScript sammenligninger

Tildel 5 til x, og vis værdien af (x == 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 8):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == 8);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x == 5)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The == Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x == 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x == 5);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x === 5)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The === Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x === 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x === 5);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x === "5")

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The === Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x === "5").</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x === "5");
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x != 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The != Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x != 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x != 8);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x !== 5)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The !== Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x !== 5):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x !== 5);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x !== "5")

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The !== Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x !== "5"):</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x !== "5");
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x > 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &gt; Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &gt; 8).</p>
 
<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x > 8);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x < 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &lt; Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &lt; 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x < 8);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x >= 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &gt;= Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &gt;= 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x >= 8);
</script>

</body>
</html>

Tildel 5 til x, og vis værdien af (x <= 8)

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Comparison</h1>
<h2>The &lt;= Operator</h2>

<p>Assign 5 to x, and display the value of the comparison (x &lt;= 8).</p>

<p id="demo"></p>

<script>
let x = 5;
document.getElementById("demo").innerHTML = (x <= 8);
</script>

</body>
</html>

Sammenligninger forklaret


JavaScript-betingelser

Hvis-erklæringen

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if</h2>

<p>Display "Good day!" if the hour is less than 18:00:</p>

<p id="demo">Good Evening!</p>

<script>
if (new Date().getHours() < 18) {
  document.getElementById("demo").innerHTML = "Good day!";
}
</script>

</body>
</html>

Den anden udtalelse

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if .. else</h2>

<p>A time-based greeting:</p>

<p id="demo"></p>

<script>
const hour = new Date().getHours(); 
let greeting;

if (hour < 18) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

document.getElementById("demo").innerHTML = greeting;
</script>

</body>
</html>

Den anden hvis erklæring

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript if .. else</h2>

<p>A time-based greeting:</p>

<p id="demo"></p>

<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>

</body>
</html>

Tilfældigt link

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Math.random()</h2>

<p id="demo"></p>

<script>
let text;
if (Math.random() < 0.5) {
  text = "<a href='https://w3schools.com'>Visit W3Schools</a>";
} else {
  text = "<a href='https://wwf.org'>Visit WWF</a>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Skift erklæring

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript switch</h2>

<p id="demo"></p>

<script>
let day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case  6:
    day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>

</body>
</html>

Betingelser forklaret


JavaScript-løkker

Til sløjfe

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
let text = "";

for (let i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Looping af et array

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];

let text = "";
for (let i = 0; i < cars.length; i++) {
  text += cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Sløjfer gennem HTML-headers

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p>Loop from 1 to 6, to make HTML headings.</p>

<div id="demo"></div>

<script>
var x ="", i;
for (i=1; i<=6; i++) {
  x = x + "<h" + i + ">Heading " + i + "</h" + i + ">";
}
document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Mens sløjfe

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript While Loop</h2>

<p id="demo"></p>

<script>
let text = "";
let i = 0;
while (i < 10) {
  text += "<br>The number is " + i;
  i++;
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Gør Mens loop

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Do While Loop</h2>

<p id="demo"></p>

<script>
let text = ""
let i = 0;

do {
  text += "<br>The number is " + i;
  i++;
}
while (i < 10);  

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Bryd en løkke

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Bryd og fortsæt en løkke

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>continue</b> statement.</p>

<p>A loop which will skip the step where i = 3.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { continue; }
  text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Sløjfer forklaret


JavaScript-fejlhåndtering

Prøv...fangst-erklæringen

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Error Handling</h2>

<p>How to use <b>catch</b> to display an error.</p>

<p id="demo"></p>

<script>
try {
  adddlert("Welcome guest!");
}
catch(err) {
  document.getElementById("demo").innerHTML = err.message;
}
</script>

</body>
</html>

Try...catch-erklæringen med en bekræftelsesboks

<!DOCTYPE html>
<html>

<script>
var txt = "";
function message() {
  try {
    adddlert("Welcome guest!");
  }
  catch(err) {
    txt = "There was an error on this page.\n\n";
    txt += "Click OK to continue viewing this page,\n";
    txt += "or Cancel to return to the home page.\n\n";
    if(!confirm(txt)) {
      document.location.href = "https://www.w3schools.com/";
    }
  }
}
</script>

<body>

<h2>JavaScript Error Handling</h2>

<input type="button" value="View message" onclick="message()" />

</body>
</html>

Fejlbegivenheden

<!DOCTYPE html>
<html>
<head>
<script>
onerror = handleErr;
var txt = "";
function handleErr(msg, url, l) {
  txt = "There was an error on this page.\n\n";
  txt += "Error: " + msg + "\n";
  txt += "URL: " + url + "\n";
  txt += "Line: " + l + "\n\n";
  txt += "Click OK to continue.\n\n";
  alert(txt);
  return true;
}

function message() {
   adddlert("Welcome guest!");
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

Fejl forklaret


JavaScript regulære udtryk

Søg efter et udtryk i en streng

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Regular Expressions</h2>

<p>Search a string for "w3Schools", and display the position of the match:</p>

<p id="demo"></p>

<script>
let text = "Visit W3Schools!"; 
let n = text.search(/w3Schools/i);
document.getElementById("demo").innerHTML = n;
</script>

</body>
</html>

Søg efter et udtryk og erstat det

<!DOCTYPE html>
<html>

<body>

<h2>JavaScript String Methods</h2>

<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<button onclick="myFunction()">Try it</button>

<p id="demo">Please visit Microsoft!</p>

<script>
function myFunction() {
  let text = document.getElementById("demo").innerHTML;
  document.getElementById("demo").innerHTML =
  text.replace(/microsoft/i, "W3Schools");
}
</script>

</body>
</html>

Regulære udtryk forklaret


JavaScript objekter

Oprettelse af en JavaScript-variabel

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Variables</h2>

<p id="demo"></p>

<script>
// Create and display a variable:
let person = "John Doe";
document.getElementById("demo").innerHTML = person;
</script>

</body>
</html>

Oprettelse af et JavaScript-objekt

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating an object:</p>

<p id="demo"></p>

<script>
let person = {
  firstName : "John",
  lastName  : "Doe",
  age     : 50,
  eyeColor  : "blue"
};

document.getElementById("demo").innerHTML = person.firstName + " " + person.lastName;
</script>

</body>
</html>

Oprettelse af et JavaScript-objekt (enkelt linje)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = {firstName:"John", lastName:"Doe", age:50,eyeColor:"blue"};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Oprettelse af et JavaScript-objekt (flere linjer)

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  age: 50,
  eyeColor: "blue"
};

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Oprettelse af et JavaScript-objekt ved hjælp af ny

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>Creating a JavaScript Object:</p>

<p id="demo"></p>

<script>
const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue"; 

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Oprettelse af JavaScript-objekter ved hjælp af en konstruktør

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Constructors</h2>

<p id="demo"></p>

<script>
// Constructor function for Person objects
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + "."; 
</script>

</body>
</html>

Oprettelse af indbyggede JavaScript-objekter

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x1 = new Object();   // A new Object object
var x2 = new String();   // A new String object
var x3 = new Number();   // A new Number object
var x4 = new Boolean();  // A new Boolean object
var x5 = new Array();  // A new Array object
var x6 = new RegExp();   // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date();   // A new Date object

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>" +
"x8: " + typeof x8 + "<br>";
</script>

<p>There is no need to use String(), Number(), Boolean(), Array(), and RegExp()</p>
<p>Read the JavaScript tutorials.</p>

</body>
</html>

Den bedste måde at oprette JavaScript-variabler på

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var x1 = {};
var x2 = "";
var x3 = 0;
var x4 = false;
var x5 = [];
var x6 = /()/;
var x7 = function(){};

document.getElementById("demo").innerHTML =
"x1: " + typeof x1 + "<br>" +
"x2: " + typeof x2 + "<br>" +
"x3: " + typeof x3 + "<br>" +
"x4: " + typeof x4 + "<br>" +
"x5: " + typeof x5 + "<br>" +
"x6: " + typeof x6 + "<br>" +
"x7: " + typeof x7 + "<br>";
</script>

</body>
</html>

JavaScript-objekter kan ændres

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>
<p>JavaScript objects are mutable.</p>
<p>Any changes to a copy of an object will also change the original object:</p>

<p id="demo"></p>

<script>
const person = {
  firstName: "John",
  lastName: "Doe",
  age:50,
  eyeColor: "blue"
};

const x = person;
x.age = 10;

document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>

Objekter forklaret


JavaScript-objektegenskaber

Adgang til egenskaber ved hjælp af .property

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Access a property with .property:</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

document.getElementById("demo").innerHTML = person.firstname + " is " + person.age + " years old.";
</script>

</body>
</html>

Adgang til egenskaber ved hjælp af [egenskab]

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Access a property with ["property"]:</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

document.getElementById("demo").innerHTML = person["firstname"] + " is " + person["age"] + " years old.";
</script>

</body>
</html>

Adgang til egenskaber ved hjælp af for in

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Looping object property values:</p>

<p id="demo"></p>

<script>
const person = {
  fname:"John",
  lname:"Doe",
  age:25
}; 

let txt = "";
for (let x in person) {
  txt += person[x] + " ";
}

document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

Tilføjelse af nye egenskaber til eksisterende objekter

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Add a new property to an existing object:</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

person.nationality = "English";
document.getElementById("demo").innerHTML =
person.firstname + " is " + person.nationality + ".";
</script>

</body>
</html>

Sletning af egenskaber fra objekter

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>
<p>Deleting object properties.</p>

<p id="demo"></p>

<script>
const person = {
  firstname: "John",
  lastname: "Doe",
  age: 50,
  eyecolor: "blue"
};

delete person.age;

document.getElementById("demo").innerHTML =
person.firstname + " is " + person.age + " years old.";
</script>

</body>
</html>

Objektegenskaber forklaret


JSON-objekter

Adgang til egenskaber ved hjælp af .property

<!DOCTYPE html>
<html>
<body>

<h2>Access a JavaScript Object</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>

</body>
</html>

Adgang til egenskaber ved hjælp af [egenskab]

<!DOCTYPE html>
<html>
<body>

<h2>Access a JavaScript Object</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj["name"];
</script>

</body>
</html>

Sløjfe gennem ejendomme

<!DOCTYPE html>
<html>
<body>

<h2>Looping Object Properties</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Gennemgang af ejendomsværdier

<!DOCTYPE html>
<html>
<body>

<h2>Looping JavaScript Object Values</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += myObj[x] + ", ";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Få adgang til indlejrede JSON-objekter

<!DOCTYPE html>
<html>
<body>

<h2>Access Nested JavaScript Objects</h2>
<p id="demo"></p>

<script>
const myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
document.getElementById("demo").innerHTML = myObj.cars.car2;
</script>

</body>
</html>

Rediger værdier ved hjælp af punktnotationen

<!DOCTYPE html>
<html>
<body>

<p>Modify object values:</p>

<p id="demo"></p>

<script>
let x = "";
let myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
myObj.cars.car2 = "Mercedes";

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Rediger værdier ved hjælp af parentesnotation

<!DOCTYPE html>
<html>
<body>

<p>Modify object values using bracket notation:</p>

<p id="demo"></p>

<script>
let x = "";
let myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
myObj.cars["car2"] = "Mercedes";

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Slet objektegenskaber

<!DOCTYPE html>
<html>
<body>

<h2>Delete JavaScript Object Properties</h2>

<p id="demo"></p>

<script>
let x = "";
let myObj = {
  "name":"John",
  "age":30,
  "cars": {
  "car1":"Ford",
  "car2":"BMW",
  "car3":"Fiat"
  }
}
delete myObj.cars.car2;

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JSON-objektegenskaber forklaret


JSON-arrays

Adgang til matrixværdier

<!DOCTYPE html>
<html>
<body>

<h2>Access Array Values</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
const myObj = JSON.parse(myJSON);

document.getElementById("demo").innerHTML = myObj.cars[0];
</script>

</body>
</html>

Sløjfe gennem et array ved hjælp af for-in

<!DOCTYPE html>
<html>
<body>

<h2>Looping an Array</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
const myObj = JSON.parse(myJSON);

let text = "";
for (let i in myObj.cars) {
  text += myObj.cars[i] + ", ";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Sløjfe gennem et array ved hjælp af for

<!DOCTYPE html>
<html>
<body>

<h2>Looping an Array</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "cars":["Ford", "BMW", "Fiat"]}';
const myObj = JSON.parse(myJSON);

let text = "";
for (let i = 0; i < myObj.cars.length; i++) {
  text += myObj.cars[i] + ", ";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Få adgang til indlejrede JSON-arrays

<!DOCTYPE html>
<html>
<body>

<p>Looping through arrays inside arrays.</p>
<p id="demo"></p>

<script>
let x = "";
const myObj = {
  "name":"John",
  "age":30,
  "cars": [
    {"name":"Ford", "models":["Fiesta", "Focus", "Mustang"]},
    {"name":"BMW", "models":["320", "X3", "X5"]},
    {"name":"Fiat", "models":["500", "Panda"] }
  ]
}

for (let i in myObj.cars) {
  x += "<h2>" + myObj.cars[i].name + "</h2>";
  for (let j in myObj.cars[i].models) {
    x += myObj.cars[i].models[j] + "<br>";
  }
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Rediger matrixværdier

<!DOCTYPE html>
<html>
<body>

<p>Modify an array value of an object.</p>
<p id="demo"></p>

<script>
let x = "";
const myObj = {
  "name":"John",
  "age":30,
  "cars":[ "Ford", "BMW", "Fiat" ]
};

myObj.cars[1] = "Mercedes";

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

Slet array-elementer

<!DOCTYPE html>
<html>
<body>

<p>Delete array properties:</p>
<p id="demo"></p>

<script>
let x = "";
const myObj = {
  "name":"John",
  "age":30,
  "cars": ["Ford","BMW","Fiat"]
}

delete myObj.cars[1];

for (let i in myObj.cars) {
  x += myObj.cars[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</script>

</body>
</html>

JSON-arrays forklaret


JSON-parse

Brug JSON-parse

<!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>

Brug af JSON-parse i et AJAX-eksempel

<!DOCTYPE html>
<html>
<body>

<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "json_demo.txt");
xmlhttp.send();
</script>

</body>
</html>

Brug af JSON-parse på et array

<!DOCTYPE html>
<html>
<body>

<h2>Fetch a JSON file with XMLHttpRequest</h2>
<p>Content written as an JSON array will be converted into a JavaScript array.</p>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myArr = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myArr[0];
}
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();
</script>

</body>
</html>

Parsing datoer

<!DOCTYPE html>
<html>
<body>

<h2>Convert a string into a date object.</h2>
<p id="demo"></p>

<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 
</script>

</body>
</html>

Parsing af datoer ved hjælp af genoplivningsfunktionen

<!DOCTYPE html>
<html>
<body>

<h2>Convert a string into a date object.</h2>

<p id="demo"></p>

<script>
const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
  if (key == "birth") {
    return new Date(value);
  } else {
    return value;
  }
});
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth; 
</script>

</body>
</html>

Parsing funktioner

<!DOCTYPE html>
<html>
<body>

<h2>Convert a string into a function.</h2>
<p id="demo"></p>

<script>
const text = '{"name":"John", "age":"function() {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age(); 
</script>

</body>
</html>

JSON Parse Forklaret


JSON Stringify

Brug JSON stringify

<!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>

Brug af JSON stringify på et array

<!DOCTYPE html>
<html>
<body>

<h2>Create a JSON string from a JavaScript array.</h2>
<p id="demo"></p>

<script>
const arr = ["John", "Peter", "Sally", "Jane"];
const myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Stringify datoer

<!DOCTYPE html>
<html>
<body>

<h2>JSON.stringify() converts date objects into strings.</h2>
<p id="demo"></p>

<script>
const obj = {name: "John", today: new Date(), city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Stringify funktioner

<!DOCTYPE html>
<html>
<body>

<h2>JSON.stringify() will remove any functions from an object.</h2>
<p id="demo"></p>

<script>
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

Stringify-funktioner ved hjælp af toString()-metoden

<!DOCTYPE html>
<html>
<body>

<h2>JSON.stringify() will remove any functions from an object.</h2>
<p>Convert functions into strings to keep them in the JSON object.</p>

<p id="demo"></p>

<script>
const obj = {name: "John", age: function () {return 30;}, city: "New York"};
obj.age = obj.age.toString();
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
</script>

</body>
</html>

JSON Stringify forklaret


JSON PHP

Hent JSON fra en php-fil

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();
</script>

</body>
</html>

Hent JSON-array fra php

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p>Convert the data into a JavaScript array:</p>
<p id="demo"></p>

<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php");
xmlhttp.send();
</script>

</body>
</html>

Hent JSON fra en database

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p>The JSON received from the PHP file:</p>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({"limit":10});

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  document.getElementById("demo").innerHTML = this.responseText;
}
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>

</body>
</html>

Gennemgå resultatet fra en database

<!DOCTYPE html>
<html>
<body>

<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>

<script>
const obj = { "limit":10 };
const dbParam = JSON.stringify(obj);
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  myObj = JSON.parse(this.responseText);
  let text = ""
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>

<p>Try changing the "limit" property from 10 to 5.</p>

</body>
</html>

Send JSON ved hjælp af POST-metoden

<!DOCTYPE html>
<html>
<body>

<h2>Use HTTP POST to Get JSON Data from a PHP Server</h2>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  myObj = JSON.parse(this.responseText);
  let text = "";
  for (let x in myObj) {
    text += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_db_post.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>

<p>Try changing the "limit" property from 10 to 5.</p>

</body>
</html>

JSON PHP forklaret


JSON HTML

Lav en HTML-tabel baseret på JSON-data

<!DOCTYPE html>
<html>
<body>

<h2>Make a table based on JSON data.</h2>

<p id="demo"></p>

<script>
const dbParam = JSON.stringify({table:"customers",limit:20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "<table border='1'>"
  for (let x in myObj) {
    text += "<tr><td>" + myObj[x].name + "</td></tr>";
  }
  text += "</table>"    
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_html_table.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>

</body>
</html>

Lav en dynamisk HTML-tabel

<!DOCTYPE html>
<html>
<body>

<h2>Make a table based on the value of a drop down menu.</h2>

<select id="myselect" onchange="change_myselect(this.value)">
  <option value="">Choose an option:</option>
  <option value="customers">Customers</option>
  <option value="products">Products</option>
  <option value="suppliers">Suppliers</option>
</select>

<p id="demo"></p>

<script>
function change_myselect(sel) {
  const dbParam = JSON.stringify({table:sel,limit:20});
  const xmlhttp = new XMLHttpRequest();
  xmlhttp.onload = function() {
    myObj = JSON.parse(this.responseText);
    text = "<table border='1'>"
    for (x in myObj) {
      text += "<tr><td>" + myObj[x].name + "</td></tr>";
    }
    text += "</table>"    
    document.getElementById("demo").innerHTML = text;
  }
  xmlhttp.open("POST", "json_demo_html_table.php", true);
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("x=" + dbParam);
}
</script>

</body>
</html>

Lav en HTML-rulleliste baseret på JSON-data

<!DOCTYPE html>
<html>
<body>

<h2>Make a drop down list based on JSON data.</h2>
<p id="demo"></p>

<script>
const dbParam = JSON.stringify({table:"customers",limit:20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "<select>"
  for (let x in myObj) {
    text += "<option>" + myObj[x].name + "</option>";
  }
  text += "</select>"
  document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_html_table.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>

</body>
</html>

JSON HTML forklaret


JSON JSONP

Simpelt JSONP eksempel

<!DOCTYPE html>
<html>
<body>

<h2>Request JSON using the script tag</h2>
<p>The PHP file returns a call to a function that will handle the JSON data.</p>
<p id="demo"></p>

<script>
function myFunc(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

<script src="demo_jsonp.php"></script>

</body>
</html>

Opret et dynamisk script-tag

<!DOCTYPE html>
<html>

<body>

<h2>Click the Button.</h2>
<p>A script tag with a src attribute is created and placed in the document.</p>
<p>The PHP file returns a call to a function with the JSON object as a parameter.</p>

<button onclick="clickButton()">Click me!</button>

<p id="demo"></p>

<script>
function clickButton() {
  let s = document.createElement("script");
  s.src = "demo_jsonp.php";
  document.body.appendChild(s);
}

function myFunc(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

</body>
</html>

JSONP eksempel med dynamisk resultat

<!DOCTYPE html>
<html>
<body>

<p>A script tag with a src attribute is created and placed in the document.</p>
<p>The PHP file returns a call to a function with an object as a parameter.</p>
<p id="demo"></p>

<p>Try changing the table property from "customers" to "products".</p>

<script>
const obj = { table: "customers", limit: 10 };
let s = document.createElement("script");
s.src = "jsonp_demo_db.php?x=" + JSON.stringify(obj);
document.body.appendChild(s);

function myFunc(myObj) {
  let txt = "";
  for (let x in myObj) {
    txt += myObj[x].name + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>

JSONP eksempel med en tilbagekaldsfunktion

<!DOCTYPE html>
<html>
<body>

<h2>Request With a Callback Function</h2>
<p>The PHP file returns a call to the function you send as a callback.</p>
<p id="demo"></p>

<script>
let s = document.createElement("script");
s.src = "demo_jsonp2.php?callback=myDisplayFunction";
document.body.appendChild(s);

function myDisplayFunction(myObj) {
  document.getElementById("demo").innerHTML = myObj.name;
}
</script>

</body>
</html>

JSON JSONP Forklaret