array iteration
Examples of iterating, mapping, filtering, and reducing arrays.
Node.js
const array = ['a', 'b', 'c']
array.forEach((value, i) => {
console.log(i, value)
})
const mapped = array.map(value => {
return value.toUpperCase()
})
console.log(mapped)
const filtered = array.filter((value, i) => {
return i % 2 == 0
})
console.log(filtered)
const reduced = array.reduce((acc, value, i) => {
if (i % 2 == 0) {
acc.push(value.toUpperCase())
}
return acc
}, [])
console.log(reduced)
Output
0 'a'
1 'b'
2 'c'
[ 'A', 'B', 'C' ]
[ 'a', 'c' ]
[ 'A', 'C' ]
Go
package main
import (
"fmt"
"strings"
)
func main() {
array := []string{"a", "b", "c"}
for i, value := range array {
fmt.Println(i, value)
}
mapped := make([]string, len(array))
for i, value := range array {
mapped[i] = strings.ToUpper(value)
}
fmt.Println(mapped)
var filtered []string
for i, value := range array {
if i%2 == 0 {
filtered = append(filtered, value)
}
}
fmt.Println(filtered)
var reduced []string
for i, value := range array {
if i%2 == 0 {
reduced = append(reduced, strings.ToUpper(value))
}
}
fmt.Println(reduced)
}
Output
0 a
1 b
2 c
[A B C]
[a c]
[A C]
当前内容版权归 miguelmota 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 miguelmota .