let testArray = [20, "string", true, "hahha"];
- forループ
forループは、実際には標準のC言語スタイルの文法です。
for (var i = 0; i < testArray.length; i ++) {
console.log("数组的值:"+testArray[i]);
}
// 数组的值:20
// 数组的值:string
// 数组的值:true
// 数组的值:hahha
- for ... inループ
for (let index in testArray) {
console.log("数组的下标:"+index);
}
/*
数组的下标:0
数组的下标:1
数组的下标:2
数组的下标:3
*/
- for ... ofループ
for (let value of testArray) {
console.log("数组的值:"+value);
}
/*
数组的值:20
数组的值:string
数组的值:true
数组的值:hahha
*/
- forEachループ
forEachは、実際にはJavaScriptのループ構文です。JavaScriptの構文スーパーセットであるTypeScriptは、もちろんデフォルトでサポートされています。
testArray.forEach((value, index, array)=>{
console.log("value:"+value+"--index:"+index);
console.log(array);
});
/*
打印日志:
value:20--index:0
(4) [20, "string", true, "hahha"]
value:string--index:1
(4) [20, "string", true, "hahha"]
value:true--index:2
(4) [20, "string", true, "hahha"]
value:hahha--index:3
(4) [20, "string", true, "hahha"]
*/
- すべてのサイクル
every
はJavaScript
文法のサイクルであり、TypeScrip
tはJavaScript
構文のスーパーセットです。もちろん、デフォルトもサポートされています。forEach
iteration
では返せないため、every
代わりに使用できますforEach
。
every
ループ、ループ本体には値があるtrue
か、false
戻り値が必要です。
testArray.every((value, index, array) => {
return true;//类似于continue,持续当前循环
});
testArray.every((value, index, array) => {
console.log("index:"+index+"--value:"+value);
return false; //类似于break,跳出当前循环
});
// 打印日志
// index:0--value:20