---
# System prepended metadata

title: JavaScript Exercises
tags: [Javascript]

---

# JavaScript Exercises 


###### tags: `Javascript`

這是個 [w3schools](https://www.w3schools.com/js/js_exercises.asp) 提供的免費的 JS 練習題目剛好可以熟悉一些 JS 的方法，這邊我就剛好利用這個練習來整理這些用法並記錄在這篇文章中，以便未來忘記語法可以來查看

完成證明

![](https://i.imgur.com/dl6Je9q.png)


## JS Variables

第五題，他使用逗點的方式一次指派多個變數

On one single line, declare three variables with the following names and values:

firstName = "John"
lastName = "Doe"
age = 35


```javascript=
var firstName = "John", lastName = "Doe", age = 35;
```

## JS Events

使用到 onmouseover 

The` <div> `element should turn red when someone moves the mouse over it.

```html=
<div onmouseover="this.style.backgroundColor='red'">myDIV.</div>
```

## JS Strings

跳脫字元 利用反斜線來跳脫引號

Use escape characters to alert We are "Vikings".


```javascript=
var txt = "We are \"Vikings\"";
alert(txt);
```


## JS String Methods

### indexOf()

使用 `indexOf()`  找出字串內指定的字母的位置

Find the position of the character h in the string txt.

```javascript=
var txt = "abcdefghijklm";
var pos = txt.indexOf("h");

console.log(pos) // 7
```

### slice()

使用 `slice()` 從字串中切出指定的字母，(第一位字母, 最後一字母下一位)

Use the slice method to return the word "bananas".


```javascript=
var txt = "I can eat bananas all day";
var x = txt.slice(10, 17);

console.log(x) // bananas
```

### replace()

使用 `replace()` 取代字母 (原本的字母, 取代的字母)

Use the correct String method to replace the word "Hello" with the word "Welcome".


```javascript=
var txt = "Hello World";
txt = txt.replace("Hello", "Welcome");

console.log(txt) //  Welcome World
```

## JS Array Methods

### pop()

使用 `pop()` 移除**最後**一個內容

Use the correct Array method to remove the last item of the fruits array.


```javascript=
var fruits = ["Banana", "Orange", "Apple"];
fruits.pop();

console.log(fruits) // ["Bananas","Oranges"]
```

### push()

使用 `push()` **加入**內容到陣列最後

Use the correct Array method to add "Kiwi" to the fruits array.


```javascript=
var fruits = ["Banana", "Orange", "Apple"];
fruits.push("Kiwi");

console.log(fruits) // ["Banana", "Orange", "Apple", "Kiwi"]
```


### splice()

使用 `splice()` 刪除指定 index 的內容

Use the splice() method to remove "Orange" and "Apple" from fruits.


```javascript=
var fruits = ["Banana", "Orange", "Apple", "Kiwi"];
fruits.splice(1, 2);

console.log(fruits)  //  ["Banana", "Kiwi"]
```

### sort()

使用 `sort()` 讓陣列內容開頭按照 abcd... 字母順序排列

Use the correct Array method to sort the fruits array alphabetically.


```javascript=
var fruits = ["Banana", "Orange", "Apple", "Kiwi"];
fruits.sort();

console.log(fruits) // ["Apple", "Banana", "Kiwi", "Orange"]
```

## JS Dates

### setFullYear()

使用`setFullYear()` 可以指定年分

Use the correct Date method to set the year of a date object to 2020.


```javascript=
var d = new Date();
d.setFullYear(2020);

console.log(d) // Mon May 04 2020 01:54:51 GMT+0800 (Taipei Standard Time)
```

## JS Math

### Math.round()

使用 `Math.round()` 可以取得最接近的正整數

Use the correct Math method to round a number to the nearest integer.

```javascript=
var x = Math.round(5.3);

console.log(x) //5
```


### Math.sqrt()

使用 `Math.sqrt()` 可以取得開根號的結果

Use the correct Math method to get the square root of 9.


```javascript=
var x = Math.sqrt(9);

console.log(x)// 3
```

## JS Switch

比較少用複習一下

如果 fruits 是 Bananas 則跳出 Hello 如果是 Apple 則跳出 Welcome

Create a switch statement that will alert "Hello" if fruits is "banana", and "Welcome" if fruits is "apple".


```javascript=
switch(fruits) {
  
    case"Banana":
        alert("Hello")
        break;

    case"Apple":
        alert("Welcome")
        break;    
}
```

### default

如果都不是則返回 Neither

Add a section that will alert("Neither") if fruits is neither "banana" nor "apple".


```javascript=
switch(fruits) {
  case "Banana":
    alert("Hello")
    break;
  case "Apple":
    alert("Welcome")
    break;
  
    default:
    alert("Neither");
}
```

## JS For Loop


### For...of

使用 `For...of` 印出陣列所有的內容

Create a loop that runs through each item in the fruits array.


```javascript=
var fruits = ["Apple", "Banana", "Orange"];
for (x of fruits) {
  console.log(x);
}
// Apple
// Banana
// Orange
```

## JS While Loops

印出小於 10 的數字並且每次數字都會加二

Create a loop that runs as long as i is less than 10, but increase i with 2 each time.


```javascript=
var i = 0;
while (i < 10) {
  console.log(i);
  i = i + 2;
  }
  
  // 0 2 4 6 8 10
```


## JS Break Loops

### break

讓迴圈跑到 5 就停下 使用 `break`

Make the loop stop when i is 5.


```javascript=
for (i = 0; i < 10; i++) {
  console.log(i);
  if (i == 5) {
    break;
}
}
// 0 1 2 3 4 5
```

### continue

使迴圈跳過條件內容且進入下一個迭代使用 `continue`

從下方的例子來理解就是跳過 5 繼續印出其他的數字

Make the loop jump to the next iteration when i is 5.


```javascript=
for (i = 0; i < 10; i++) {
  if (i == 5) {
    continue;
}
  console.log(i);
  
}

// 0 1 2 3 4 6 7 8 9
```


## JS HTML DOM

### getElementsByTagName()

取得 HTML 內的 tag 使用`getElementsByTagName()` 操作方式使用`[index]`選取想要操作的 tag

Use the getElementsByTagName method to find the first `<p>` element, and change its text to "Hello".


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

<script>
document.getElementsByTagName("p")[0].innerHTML= "Hello";
</script>
```

### getElementsByClassName()

取得指定 class 的 HTML tag 使用 `getElementsByClassName()` 操作方式使用`[index]`選取想要操作的 tag

Change the text of the first element that has the class name "test".


```html=
<p class="test"></p>
<p class="test"></p>

<script>
document.getElementsByClassName("test")[0].innerHTML = "Hello";
</script>
```

### 操作圖片的 src

操作圖片的 src 

Use HTML DOM to change the value of the image's src attribute.


```html=
<img id="image" src="smiley.gif">

<script>
document.getElementById("image").src = "pic_mountain.jpg";
</script>
```

### 操作 input 的 value

操作 input 的 value

Use HTML DOM to change the value of the input field.


```html=
<input type="text" id="myText" value="Hello">

<script>
document.getElementById("myText").value = "Have a nice day!";
</script>
```

### 操作文字顏色改變

操作文字顏色改變

Change the text color of the `<p>` element to "red".

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

<script>
document.getElementById("demo").style.color = "red";
</script>
```

### 操作文字大小修改

操作文字大小修改

Change the font size of the p element to 40 pixels.


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

<script>
document.getElementById("demo").style.fontSize = "40px";
</script>
```

### 操作CSS position

操作CSS position

Use the CSS display property to hide the p element.


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

<script>
document.getElementById("demo").style.display = "none";
</script>
```


### 事件監聽


Use the eventListener to assign an onclick event to the `<button>` element.


```html=
<button id="demo">Click me1</button>

<script>
document.getElementById("demo").addEventListener("click", myFunction);
</script>
```