一、常用的測試寫法
//array的寫法 var myArray = ["Apple", "Orange", "Banana"]; //一、正常迴圈寫法如下: var fruitFinal3 = "" for (var i = 0; i < myArray.length; i++) { fruitFinal3 += myArray[i] + " "; } console.log("1. for loop Results: ", fruitFinal3); //二、用forEach寫法如下: var fruitFinal4 = ""; myArray.forEach(myFunction); function myFunction(value) { fruitFinal4 += value + " "; } console.log("2. forEach Results: ", fruitFinal4);
測試結果如下:
二、不用看,請略過這些奇葩想法
//三、底下都不用看,是自己瞎寫+瞎測試一些怪想法 console.log(myArray)//會顯示出這是Array型別 //存疑寫法?如下寫法在頁面上可以整體輸出內容來, document.getElementById("demo3").innerHTML = myArray; //讀取每個值,不要用這種寫法,這種寫法只列印出序號 var fruitFinal = "" for (const ele in myArray) { fruitFinal += ele+" "; } console.log("類似object寫法1?: ", fruitFinal); //如果非要按上面寫法,因為array也屬於object的一種,上面可以改寫成如下: var fruitFinal2 = "" for (const ele in myArray) { fruitFinal2 += myArray[ele] + " "; } console.log("類似object寫法2?: ", fruitFinal2);
console.log 測試結果如下:
demo3頁面的顯示如下: