1// object to loop through
2let obj = { first: "John", last: "Doe" };
3
4// loop through object and log each key and value pair
5//ECMAScript 5
6Object.keys(obj).forEach(function(key) {
7 console.log(key, obj[key]);
8});
9
10//ECMAScript 6
11for (const key of Object.keys(obj)) {
12 console.log(key, obj[key]);
13}
14
15//ECMAScript 8
16Object.entries(obj).forEach(
17 ([key, value]) => console.log(key, value)
18);
19
20// OUTPUT
21/*
22 first John
23 last Doe
24*/
1var obj = { first: "John", last: "Doe" };
2
3Object.keys(obj).forEach(function(key) {
4 console.log(key, obj[key]);
5});
1var p = {
2 "p1": "value1",
3 "p2": "value2",
4 "p3": "value3"
5};
6
7// for-in
8for (var key in p) {
9 if (p.hasOwnProperty(key)) {
10 console.log(key + " -> " + p[key]);
11 }
12}
13
14// for-of with Object.keys()
15for (var key of Object.keys(p)) {
16 console.log(key + " -> " + p[key])
17}
18
19// Object.entries()
20for (let [key, value] of Object.entries(p)) {
21 console.log(`${key}: ${value}`);
22}
1const rgb = [255, 0, 0];
2
3// Randomly change to showcase updates
4setInterval(setContrast, 1000);
5
6function setContrast() {
7 // Randomly update colours
8 rgb[0] = Math.round(Math.random() * 255);
9 rgb[1] = Math.round(Math.random() * 255);
10 rgb[2] = Math.round(Math.random() * 255);
11
12 // http://www.w3.org/TR/AERT#color-contrast
13 const brightness = Math.round(((parseInt(rgb[0]) * 299) +
14 (parseInt(rgb[1]) * 587) +
15 (parseInt(rgb[2]) * 114)) / 1000);
16 const textColour = (brightness > 125) ? 'black' : 'white';
17 const backgroundColour = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
18 $('#bg').css('color', textColour);
19 $('#bg').css('background-color', backgroundColour);
20}