この記事では、JavaScript のトラバーサル メソッド (コード例) を紹介します。必要な方は参考にしていただければ幸いです。
オブジェクトオブジェクトを配列に変換すると便利なので、トラバース方法を思いついたので、それも記録したいと思います
1。ループから抜け出す
偽のデータ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | const temporaryArray = [6,2,3,4,5,1,1,2,3,4,5];
const objectArray = [
{
id: 1,
name: 'd'
}, {
id: 2,
name: 'd'
}, {
id: 3,
name: 'c'
}, {
id: 1,
name: 'a'
}
];
const temporaryObject = {
a: 1,
b: 2,
c: 3,
d: 4,
};
const length = temporaryArray.length;
|
ログイン後にコピー
通常の for ループ トラバーサル
1 2 3 | for (let i = 0; i < length; i++) {
console.log(temporaryArray[i]);
}
|
ログイン後にコピー
for in ループ
1 2 3 4 5 6 7 8 9 10 11 | for (let i in temporaryObject) {
if (temporaryObject.hasOwnProperty(i)) {
console.log(temporaryObject[i]);
}
}
|
ログイン後にコピー
for of ループ。反復可能なオブジェクトを走査するために使用されます。
1 2 3 | for (let i of temporaryArray) {
console.log(i);
}
|
ログイン後にコピー
forEach first 最初の値は配列の現在のインデックスの値で、2 番目の値は配列の現在のインデックスの値です。インデックス値のみを実行でき、戻り値はなく、ループから抜け出すことはできません。
1 2 3 | let a = temporaryArray.forEach( function (item, index) {
console.log(index, item);
});
|
ログイン後にコピー
map Return 新しい配列は実行のみ可能です。 array
1 2 3 | temporaryArray.map( function (item) {
console.log(item);
});
|
ログイン後にコピー
filter は配列の組み込みオブジェクトであり、元の配列を変更せず、戻り値
を持ちます。 -
1 2 3 | temporaryArray.filter( function (item) {
console.log(item%2 == 0);
});
|
ログイン後にコピー
some は一致する値があるかどうかを決定します
1 2 3 4 | let newArray = temporaryArray.some( function (item) {
return item > 1;
});
console.log(newArray);
|
ログイン後にコピー
every は配列内のすべての値があるかどうかを決定します条件を満たします
-
1 2 3 4 | let newArray1 = temporaryArray.every( function (item) {
return item > 6;
});
console.log(newArray1);
|
ログイン後にコピー
#reduce(function(total, currentValue, currentIndex, array) {}, [])
1 2 3 4 5 6 7 8 9 | let temporaryObject3 = {};
let newArray2 = objectArray.reduce( function (countArray, currentValue) {
temporaryObject3[currentValue.id] ? '' : temporaryObject3[currentValue.id] = true && countArray.push(currentValue);
return countArray;
}, []);
console.log(newArray2);
|
ログイン後にコピー
以上がJavaScriptトラバーサルメソッドの紹介(コード例)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。