【问题标题】:Is there any option to make it work? global+local varriable [closed]有没有办法让它工作?全局+局部变量[关闭]
【发布时间】:2019-05-27 05:41:03
【问题描述】:

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

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

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

【问题讨论】:

  • return players?
  • 您的问题中只声明了一个变量。 global and local variables 方面在哪里?
  • 根据@CertainPerformance,您是否希望函数实际返回。因为它确实可以满足您的需求。同意以这种方式影响变量不是最佳做法。
  • 对不起,您的问题有太多不协调之处,无法准确回答。请澄清。

标签: javascript


【解决方案1】:

这是 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;    
}

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 2010-12-30
    • 2023-01-22
    • 2012-09-25
    • 2021-11-12
    • 2012-04-29
    • 1970-01-01
    • 2013-09-27
    相关资源
    最近更新 更多