javascript - 在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暂存器来运行我的程序。
解决方案
推荐阅读
- spring-mvc - Spring中的@ConfigurationProperties不是springboot
- php - 无法删除 php 5.6+ 中的目录?
- html - 如何在a后面添加模糊?
- r - 添加索引取决于R中数据框中其他列中的变量?
- javascript - 长按退格键然后字数不刷新
- java - 如何覆盖 ChannelSftp.lstat 方法以便在 Jsch 中返回 false 而不是 SftpException
- c# - 2个应用程序c#之间的请求回复模式
- go - Golang 从 StdinPipe 清除内容
- sql - 查询中的 SQL 行为
- camera - 播放相机动画 - 虚幻蓝图