loop for in code example
Example 1: loop an object in javascript
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
Example 2: loop in object javascript
var person = {"name":"Rasel", age:26};
for (var property in person) {
console.log(person[property]);
}
Example 3: for in javascript
const object = {a: 1, b: 2, c: 3};
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
Example 4: for in loop javascript
var person = {"name":"taylor","age":31};
for (property in person) {
console.log(property,person[property]);
}
Example 5: for in loop javascript
let array = [1,2,3,4,5,6,7,8,9,10];
for (let i = 0; i < array.length; i++) {
console.log(array[i]);
}
Example 6: for in loop javascript
function diagonalDifference(arr) {
let n = arr.length;
let pri,sec = 0;
pri = sec = 0;
for (let i= 0; i < n; i++) {
pri += arr[i][i];
sec += arr[i][n - i - 1];
}
if(pri==sec){
return (0);
}else {
if (pri>sec){
return (pri-sec);
}else{
return (sec-pri);
}
}
}