首页 > 解决方案 > 在javascript中调用提升函数时的奇怪效果

问题描述

我是 JavaScript 的新手。我在 JS 中学习了提升行为,并通过一个简单的程序示例自己测试了它。

我的程序生成一个包含随机数的 Array,然后调用unique()who 删除 Array 内的所有重复元素:

const NUMBERS = [34, 25, 45, 11, 36, 98, 58, 97, 56]
const ARRAY_LENGTH = 4;
  
function getRandomNumberList () {
  let res = []
  for (i = 0; i < ARRAY_LENGTH; i++) {
    res.push(NUMBERS[Math.floor(Math.random() * ARRAY_LENGTH)])
  }
  return res
}


// Generate array with random numbers 
let randomArray = getRandomNumberList() 

// When we compute this, First call doesn't Work
// the console.log return [ 34, 45, 34, 34 ]
console.log(randomArray)

// First call with Hoisting
// Because of console log, return [ 34, 45, 25 ] instead of [ 34, 45 ]
unique(randomArray)    

// This function remove duplicates entries if exist.  
function unique (arr) {
   let uniqueArray = [...new Set(arr)]  
   return uniqueArray 
};

// Second call without hoisting. This seems to work all the time
// return [ 34, 45 ]
unique(randomArray)

然而,我遇到了一个奇怪的行为。

console.log 当我在第一个电话上方打电话时,第一个电话不起作用。但是,如果我删除了 console.log(),它似乎可以工作。

谁能解释一下为什么会发生这种行为?

请注意,我使用RunJS暂存器来运行我的程序。

标签: javascripthoisting

解决方案


推荐阅读