英文:
variable value is not changing when i am changing the value with a function in js
问题
The fill_gaps()
function is intended to modify the sec
value, but it's not changing the value outside the function because the changes made to the candidate
variable inside the function do not affect the sec
variable outside the function. Here's the corrected code:
function show() {
let date_ = new Date();
let sec = String(date_.getSeconds());
sec = fill_gaps(sec); // Update sec with the result of fill_gaps
function fill_gaps(candidate) {
if (candidate.length < 2) {
candidate = "0" + candidate;
}
return candidate; // Return the modified value
}
time_ = String(`${sec}`);
console.log(time_);
}
Now, the sec
variable is updated with the result of the fill_gaps
function, and it will display the expected output.
英文:
function show() {
let date_ = new Date();
let sec = String(date_.getSeconds());
fill_gaps(sec);
function fill_gaps(candidate) {
if (candidate.length < 2) {
candidate = "0" + candidate;
} else {
candidate = candidate;
}
}
time_ = String(`${sec}`);
console.log(time_)
}
The fill_gaps()
function is supposed to change the var sec value; but it isn't changing the value outside the function. My guess is that it is not changing on global scope.
I know this is a basic problem but I can't figure it out as I am still a beginer.
Expected:
console.log(time_) = 0("and the current second")
Actual:
console.log(tiem_) = ("the current second")
答案1
得分: 2
function show() {
let date_ = new Date();
let sec = String(date_.getSeconds());
sec = fill_gaps(sec); // 调用你的函数如此,将其值保存在 sec 变量中
time_ = String(`${sec}`);
console.log(time_)
}
// 这个在外面,它是一个单独的函数
function fill_gaps(candidate) {
if (candidate.length < 2) {
candidate = "0" + candidate;
} else {
candidate = candidate;
}
return candidate; // 你遗漏了一个返回语句
}
show();
英文:
Edit: You were missing a return statement in your fill_gaps
function, you were calling it but you weren't doing anything with it
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function show() {
let date_ = new Date();
let sec = String(date_.getSeconds());
sec = fill_gaps(sec); //call your function like this, save its value inside the sec variable
time_ = String(`${sec}`);
console.log(time_)
}
//this outside, it is a separate function
function fill_gaps(candidate) {
if (candidate.length < 2) {
candidate = "0" + candidate;
} else {
candidate = candidate;
}
return candidate;//you were missing a return statement
}
show();
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论