有没有使其工作的选择?全球+本地可变

时间:2018-12-30 01:59:48

标签: javascript

我是JavaScript新手,使用全局变量和局部变量时遇到问题。我希望函数“ check”返回[1、2、3]。在此先感谢:)

const players = [1, 2, 3, 4];

check();    
function check()    
{     
    players.pop();    
    console.log(players);    
}

1 个答案:

答案 0 :(得分:0)

这是w浅表复制的示例,在这种情况下可以使用

const players = [1, 2, 3, 4];

check();    
function check()    
{   
    // CAUTION : This is only a shallow copy and will work with value types
    // If you use on ref types, it will be pointing to the same objects.
    let innerArr = players.slice();
    innerArr.pop();    
    console.log(players); 
    console.log(innerArr);
    return innerArr;    
}