对象和数组有很多内置的方法,可以帮助您处理数据。
注意:在我使用的许多例子中
arrow functions
. 它们类似于
function expressions
,但它们将
this
重视词汇。
object.keys()
返回对象键的数组,
object.values()
返回对象值的数组,并且
object.entries()
以某种格式返回对象键和相应值的数组
[key, value]
.
const obj = {
a: 1
,b: 2
,c: 3
}
console.log(Object.keys(obj)) // ['a', 'b', 'c']
console.log(Object.values(obj)) // [1, 2, 3]
console.log(Object.entries(obj)) // [['a', 1], ['b', 2], ['c', 3]]
object.entries()
带for循环和解构赋值
const obj = {
a: 1
,b: 2
,c: 3
}
for (const [key, value] of Object.entries(obj)) {
console.log(`key: ${key}, value: ${value}`)
}
迭代
object.entries()
用一个
for-of loop
和
destructuring assignment
.
for of循环允许您迭代数组元素。语法是
for (const element of array)
我们可以替代
const
具有
var
或
let
,但最好使用
康斯特
如果我们不打算修改
element
)
解构赋值允许您从数组或对象中提取值并将它们赋给变量。在这种情况下
const [key, value]
也就是说,不是指定
[关键,价值]
数组到
要素
,我们将该数组的第一个元素分配给
key
第二个元素
value
. 相当于:
for (const element of Object.entries(obj)) {
const key = element[0]
,value = element[1]
}
正如你所看到的,破坏使这更简单。
这个
every()
方法返回
true
如果指定的回调函数返回
真
对于
每一个
数组的元素。这个
some()
方法返回
真
如果指定的回调函数返回
真
对于
一些
(至少一个)元素。
const arr = [1, 2, 3]
// true, because every element is greater than 0
console.log(arr.every(x => x > 0))
// false, because 3^2 is greater than 5
console.log(arr.every(x => Math.pow(x, 2) < 5))
// true, because 2 is even (the remainder from dividing by 2 is 0)
console.log(arr.some(x => x % 2 === 0))
// false, because none of the elements is equal to 5
console.log(arr.some(x => x === 5))
这个
find()
方法返回
第一
满足所提供回调函数的元素。这个
filter()
方法返回
全部的
满足所提供回调函数的元素。
const arr = [1, 2, 3]
// 2, because 2^2 !== 2
console.log(arr.find(x => x !== Math.pow(x, 2)))
// 1, because it's the first element
console.log(arr.find(x => true))
// undefined, because none of the elements equals 7
console.log(arr.find(x => x === 7))
// [2, 3], because these elements are greater than 1
console.log(arr.filter(x => x > 1))
// [1, 2, 3], because the function returns true for all elements
console.log(arr.filter(x => true))
// [], because none of the elements equals neither 6 nor 7
console.log(arr.filter(x => x === 6 || x === 7))
这个
map()
方法返回一个数组,其中包含对数组元素调用提供的回调函数的结果。
const arr = [1, 2, 3]
console.log(arr.map(x => x + 1)) // [2, 3, 4]
console.log(arr.map(x => String.fromCharCode(96 + x))) // ['a', 'b', 'c']
console.log(arr.map(x => x)) // [1, 2, 3] (no-op)
console.log(arr.map(x => Math.pow(x, 2))) // [1, 4, 9]
console.log(arr.map(String)) // ['1', '2', '3']
这个
reduce()
方法通过使用两个元素调用提供的回调函数将数组缩减为单个值。
const arr = [1, 2, 3]
// Sum of array elements.
console.log(arr.reduce((a, b) => a + b)) // 6
// The largest number in the array.
console.log(arr.reduce((a, b) => a > b ? a : b)) // 3
这个
约化()
方法接受可选的第二个参数,即初始值。当您调用的数组
约化()
可以有零或一个元素。例如,如果我们想要创建一个函数
sum()
它接受一个数组作为参数并返回所有元素的和,我们可以这样写:
const sum = arr => arr.reduce((a, b) => a + b, 0)
console.log(sum([])) // 0
console.log(sum([4])) // 4
console.log(sum([2, 5])) // 7