プログラミングライフスタイル
Javascript問題集

Javascript問題集(繰り返し)解答

「Javascript問題集(繰り返し)」の解答は下記になります。

問題1の解答

let foods = ["Pizza", "Curry", "Steak", "Seafood Paella", "Spaghetti Bolognese"];

for (let i = 0; i < foods.length; i++) {
	console.log(foods[i]);
}

問題2の解答

for (let i = 0; i <= 10; i++) {
	console.log(2 ** i);
}

問題3の解答

for (let i = 3; i <= 15; i += 3) {
	console.log(i);
}

問題4の解答

for (let i = 2 i <= 10; i += 2) {
	console.log(i);
}

問題5の解答

let book = {name: "delicious food", pageVolume: 102, price: 1580};

for (let key in book) {
	if (book.hasOwnProperty(key)) {
		console.log(key + ": " + book[key]);
	}
}

問題6の解答

let product = {name: "cream", weight: 30, price: 1280};

for (let key in product) {
	console.log(key + ": " + product[key]);
}

問題7の解答

for (let i = 1; i <= 5; i++) {
	console.log(i);
}

問題8の解答

let buildings = ["Sydney Opera House", "Taj Mahal", "Statue of Liberty", "Leaning Tower of Pisa"];

for (let building of buildings) {
	console.log(building);
}

問題9の解答

let numbers = [33, 78, 21, 37, 52, 32];
let sum = numbers.reduce((acc, cur) => acc + cur);

console.log(sum);

問題10の解答

let countries = ["Spain", "Canada", "Germany", "Australia", "Japan"];

for (let i = 0; i < countries.length; i++) {
	console.log(countries[i].length);
}

問題11の解答

let numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
	sum += numbers[i];
}

console.log(sum);

問題12の解答

let numbers = [1, 3, 6, 2, 3, 8, 1, 5, 8, 2, 1];
let uniqueNumbers = [];

for (let number of numbers) {
	if (!uniqueNumbers.includes(number)) {
		uniqueNumbers.push(number);
	}
}

console.log(uniqueNumbers); 

問題13の解答

const array = ["car", "bus", "ship", "plain", "train"];

for (let i = 0; i < array.length; i++) {
	console.log(array[i]);
}

問題14の解答

let sum = 0;
let i = 1;

while (i <= 1000) {
	if (i % 3 === 0) {
		sum += i;
	}
	i++;
}

console.log(sum);

問題15の解答

「for...in」はオブジェクトに対して利用するが、「for...of」は配列に対して利用する。

(例)
■for...in

let shop = {
	name: 'relax ship',
	phone:'111-xxx-2222',
	prefecture: 'Tokyo'
}

for( let data in shop){
	console.log(data); //keyが表示される
	console.log(shop[data]); //valueが表示される
} 

(例)
■for...of

let numbers = [22, 12, 56, 32, 78];

for (let number of numbers) {
	console.log(number);
}

問題16の解答

let numbers = [23, 25, 32, 54, 12 ,23, 76 ,87, 35];
let max = numbers[0];

for (let i = 1; i < numbers.length; i++) {
	if (numbers[i] > max) {
		max = numbers[i];
	}
}

console.log(max);

問題17の解答

for (let i = 10; i >= 1; i--) {
	console.log(i);
}

問題18の解答

let sum = 0;
let num;

do {
	num = parseInt(prompt("数値を入力してください(処理終了するには「0」を入力してください。)"));
	sum += num;
} while (num !== 0);

console.log(sum);

問題19の解答

const str = "Programming";

for (let i = 0; i < str.length; i++) {
	console.log(str[i]);
}

問題20の解答

const array = ["apple", "banana", "cherry"];

for (let i = 0; i < array.length; i++) {
	console.log(array[i]);
}

→(前へ)「JavaScript(繰り返し)」の問題

→(次へ)「JavaScript(配列)」の問題

HOMEへ