简体   繁体   English

扩散元素在这里起作用的目的是什么

[英]What purpose does the spread element serve here

I'm learning react from a book and in an example the author made a component render this way 我正在学习一本书的反应,在一个例子中,作者用这种方式渲染了一个组件

return (
        <div className="star-rating">
        {[...Array(totalStars)].map((n,i)=>
            <Star key = {i} selected={i<starSelected} onClick={()=>this.change(i+1)} />
        )}
        <p>{starsSelected} of  {totalStars} stars </p>+
    )

What purpose does the spread element serve here when initializing the array? 初始化数组时,spread元素的用途是什么?

Array(totalStars) makes an array with totalStars number of empty slots. Array(totalStars)创建一个包含totalStars空插槽数的数组。 Using the spread operator coerces the empty slots into undefined , effectively filling the array with SOMETHING to be mapped over (even if it is undefined). 使用spread运算符将空槽强制转换为undefined ,有效地填充数组,并使用SOMETHING进行映射(即使它未定义)。

Just instantiating an Array with Array() doesn't put anything in it's spaces, just allocates the space for them. 只使用Array()实例化一个数组不会在其空间中放置任何内容,只需为它们分配空间即可。

Spread operator means when we want things to be spread in form of array like - 传播运算符意味着当我们希望事物以数组的形式传播时 -

function ABC (...) {

console. log(...); //this will print as array [1,3,5]

}

ABC(1,3,5);

When we make call to function, we are just passing as parameters not as array. 当我们调用函数时,我们只是作为参数而不是数组传递。 But they coverted into form of Array with spread operators. 但他们用扩散算子转换成阵列形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM