console.log(monday[1], 'is Chinese for', monday[0]);
Arrays and Objects
An array can contain objects:
const weekdays = [
{english: 'Monday', chinese: '星期一'],
{english: 'Tuesday', chinese: '星期二'},
{english: 'Wednesday', chinese: '星期三'},
{english: 'Thursday', '星期四'},
{english: 'Friday', '星期五'},
{english: 'Saturday', chinese: '星期六'},
{english: 'Sunday', chinese: '星期天'}
];
const monday = weekdays[0];
console.log(monday.chinese, 'is Chinese for', monday.english);
An object can have properties whose values are arrays. Here’s another way to represent a rectangle, where each point is represented just as an array of[x, y], instead of as an object.
Here are four ways to define a function, and apply it to each element of an array. Each of these does the same thing: it prints Monday has 6 letters on a line of the console, Tuesday has 6 letters on the next line, Wednesday has 9 letters, and so on.
Objects
const point = {
x: 10,
y: 20
}
const point = {x: 10, y: 20};
console.log('x is', point.x);
const rect = {
topLeft: {x: 10, y: 20},
bottomRight: {x: 120, y: 400}
};
console.log('width =', rect.bottomRight.x - rect.topLeft.x);
Arrays
const weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
console.log(weekdays[2]);
const weekdays = [['Monday', '星期一'], ['Tuesday', '星期二'], ]'Wednesday', '星期三'], ['Thursday', '星期四'], ['Friday', '星期五'], ['Saturday', '星期六'], ['Sunday', '星期天']];
const monday = weekdays[0];
console.log(monday[1], 'is Chinese for', monday[0]);
Arrays and Objects
const weekdays = [
{english: 'Monday', chinese: '星期一'],
{english: 'Tuesday', chinese: '星期二'},
{english: 'Wednesday', chinese: '星期三'},
{english: 'Thursday', '星期四'},
{english: 'Friday', '星期五'},
{english: 'Saturday', chinese: '星期六'},
{english: 'Sunday', chinese: '星期天'}
];
const monday = weekdays[0];
console.log(monday.chinese, 'is Chinese for', monday.english);
const rectangle = {
topLeft: [10, 20],
bottomRight: [120, 400]
};
console.log('width =', rect.bottomRight[0] - rect.topLeft[0]);
Functions and forEach
function printStringAndLength(str) {
console.log(str, 'has', str.length, 'letters');
}
weekdays.forEach(printStringAndLength);
const printStringAndLength = (str) => {
console.log(str, 'has', str.length, 'letters');
}
weekdays.forEach(printStringAndLength);
const printStringAndLength = (str) =>
console.log(str, 'has', str.length, 'letters');
weekdays.forEach(printStringAndLength);
function printStringAndLength(str) {
console.log(str, 'has', str.length, 'letters');
}
weekdays.forEach((str) => console.log(str, 'has', str.length, 'letters'));