ES5 provides follow some useful Array methods, these are all available in modern browsers(>= IE9):
Array.isArrayArray.prototype.forEachArray.prototype.mapArray.prototype.everyArray.prototype.someArray.prototype.filterArray.prototype.reduceArray.prototype.reduceRight- ...
These methods are good at semantic, So use them instead of unreadable and long for-loop:
const arr = [balabala...]
const filtered = []
for(let i = 0; i < arr.length; i++) {
if (some-condition) {
filtered.push(arr[i])
}
}
// better
const arr = [balabala...]
const filtered = arr.filter((item) => some-condition)In addition, ES6(2015) provides:
- Array.from
- find
- keys
- values
- entries
- fill
and ES7(2016) provides:
- includes
Not all browsers supported these methods natively, but you can use them through babel or polyfills.
if (arr.indexOf(item) !== -1) {...}
// better
if (arr.includes(item)) {...}