JS 中的三个点“...”——扩展和剩余部分的解释
三点符号...
是 JavaScript 开发人员最喜欢的符号之一,因为它有很多用例,可以让他们的工作更轻松。
嗯,你可以在 JS 概念中看到这个运算符——spread、rest。在开始之前,让我先明确一点,两者的语法相同,但用例不同。
由于语法相同,这可能会让人感到困惑,尤其是在面试的时候(你可能会很紧张),面试官可能会试图在这方面刁难你。相信我,我在第一次 JS 面试时就犯过这方面的错误😅。
传播
展开运算符用于拆分数组元素或对象属性(因此,名称为展开,即“将数组/对象的元素展开到新数组/对象中”)。让我们理解一下我刚才说的话。
const newArray = [...oldArray, 1, 2]
const newObject = [...oldObject, newProp : 'a']
您可以快速查看下面的示例以更好地理解它
-数组
const numbers = [1, 2, 3, 4]
const numbers_with_spread = [...numbers, 5, 6]
const numbers_without_spread = [numbers, 5, 6]
console.log(numbers_with_spread)
console.log(numbers_without_spread)
您将获得如下输出
[1, 2, 3, 4, 5, 6]
[[1, 2, 3, 4], 5, 6]
-对象
现在,让我们用对象检查一下
const human = {
name : "Kedar"
}
const human_age_with_spread = {
...human,
age : '21'
}
const human_age_without_spread = {
human,
age : '21'
}
console.log(human_age_with_spread)
console.log(human_age_without_spread)
你得到的输出是
[object Object] {
age: "21",
name: "Kedar"
}
[object Object] {
age: "21",
human: [object Object] {
name: "Kedar"
}
}
休息
我们可以说它是一个数组中剩余元素的集合(因此得名 rest,即“剩余元素”)。它主要用于将函数参数列表合并到一个数组中。也就是说,当你不知道有多少个参数要传递给方法时,可以使用它。
让我们看一个例子
const more_than_three = (...args) => {
console.log(args) /* lets see what's in args */
return console.log(args.filter((x) => x > 3))
}
more_than_three(1,2,3,4,5,6,7,8)
您将收到以下输出
[1, 2, 3, 4, 5, 6, 7, 8]
[4, 5, 6, 7, 8]
哇!就是这样!
这只是为了让事情清楚。当然,如果你想深入了解文档传播,其余的是最好的选择。
希望您现在清楚这一点,祝您
学习愉快!
--
以下是我的其他一些帖子,可能对您有帮助。
鏂囩珷鏉ユ簮锛�https://dev.to/kedark/ Three-dots-in-js-spread-and-rest-explained-40e如果我分享的帖子或资源对您有所帮助,请考虑请我喝杯咖啡。这不仅能帮我支付学费,还能鼓励我与大家分享精彩实用的东西。