[英]JavaScript function gives expected result in the console, but unable to assign result to a variable
I'm unable to assign the result of a function call to a variable.我无法将 function 调用的结果分配给变量。
Let's start with the following object:让我们从下面的 object 开始:
let employees = [
{
id : 1,
name : 'John Smith',
age : 48,
salary : 100000
},
{
id : 2,
name : 'Mary Jones',
age : 29,
salary : 78000,
},
{
id : 3,
name : 'Philip Lee',
age : 36,
salary : 160000,
}
]
I have a function that accesses each employee's salary (except Mary) and applies a 20% increase:我有一个 function 访问每个员工的工资(玛丽除外)并应用 20% 的增长:
function applySalaryIncrease(employees) {
for (let i=0; i < employees.length; i++) {
if (i == 1){
continue;
}
employees[i].salary = employees[i].salary * 1.2;
}
}
Next, I submit the following in the console :接下来,我在控制台中提交以下内容:
applySalaryIncrease(employees)
employees
And, I see in the console that the salaries for John and Philip have increased, as expected.而且,我在控制台中看到 John 和 Philip 的工资按预期增加了。
However, when I assign the result to a variable named updatedEmployees
, the result in the console is undefined
.但是,当我将结果分配给名为updatedEmployees
的变量时,控制台中的结果是undefined
。
updatedEmployees = applySalaryIncrease(employees)
Why is this happening?为什么会这样?
Thanks!谢谢! (JavaScript rookie here) (这里是 JavaScript 菜鸟)
Your function isn't return
ing anything explicitly , so it returns what JavaScript functions without an explicit return value deliver, which is undefined
.您的 function 没有明确地return
任何东西,因此它返回没有明确返回值的 JavaScript 函数,这是undefined
的。
Fix it:修理它:
function applySalaryIncrease(employees) {
for (let i=0; i < employees.length; i++) {
if (i == 1){
continue;
}
employees[i].salary = employees[i].salary * 1.2;
}
return employees; // <-- explicitly return employees here
}
Usually it's not the best idea to mutate function arguments, so as long as all the array objects simply hold primitive data types, it's usually preferrable to create a shallow copy of the array passed:通常,改变 function arguments 并不是最好的主意,因此只要所有数组对象都简单地保存原始数据类型,通常最好创建传递的数组的浅表副本:
function applySalaryIncrease(emps) {
const employees = [...emps]; // this avoids mutating the array passed to the function
for (let i=0; i < employees.length; i++) {
if (i == 1){
continue;
}
employees[i].salary *= 1.2;
}
return employees; // <-- explicitly return employees here
}
You are not returning any values so your variable gets undefined as a return from the function.您没有返回任何值,因此您的变量未定义为 function 的返回。 However if you add a return employees
before closing your function and after your loop it will return it.但是,如果您在关闭 function 之前添加return employees
,并且在循环之后它将返回它。
Edit: I just saw it but it is exactly like the guy above me said编辑:我刚看到,但和我上面那个人说的一模一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.