我一直在做一个简单的反应项目,在那里我发现了这个片段。
let hand1 =[]
let hand2 =[ ...this.props.pokemon];
while(hand1.length < hand2.length){
let randIdx = Math.floor(Math.random()*hand2.length);
let randPokemon = hand2.splice(randIdx,1)[0];
hand1.push(randPokemon)
}..this.props.pokemon在这里有什么用?
发布于 2021-09-09 02:53:55
是 扩展语法(.)
在您的示例中,它从pokemon中深入复制props数组,并防止原始数组/对象发生变异。
在这个示例中,不使用spread syntax ::
const firstArray = [1, 2];
const secondArray = firstArray;
secondArray[0] = 9;
console.log(firstArray);
这里是spread syntax 使用的时间
const firstArray = [1, 2];
const secondArray = [...firstArray];
secondArray[0] = 9;
console.log(firstArray);
发布于 2021-09-09 02:56:11
let hand2 = [ ...this.props.pokemon]上面的表达式接受this.props.pokemon中的所有值,并将其放入hand2数组中。
例如:
const fruits = ['apple', 'banana']
const breakfast = [...fruits, 'milk']
console.log(breakfast) -> ['apple', 'banana', 'milk']而如果没有扩展运算符(.)。它将把整个数组放在那里,而不仅仅是值。例如:
const fruits = ['apple', 'banana']
const breakfast = [fruits, 'milk']
console.log(breakfast) -> [['apple', 'banana'], 'milk']https://stackoverflow.com/questions/69111603
复制相似问题