我正在尝试编写一个 for in 循环,该循环遍历对象并将任何大于 10 的值更改为 0。
var obj = {
one: 1,
two: 25,
three: 3,
four: 10,
five: 15,
six: 55,
}
function greaterThan10(list)
{
for (var prop in list){
if (list[prop] > 10){
list[prop] = 0;
console.log(list)
return list;
}
}
}
greaterThan10(obj)
控制台输出:
{ 一: 1, 二: 0, 三: 3, 四: 10, 五: 15, 六: 55 }
当您遇到值大于 10 的第一个属性时,您将从函数返回。这还为时过早,因为您希望在返回之前处理所有属性。只需将return list
语句移动到for
循环之后即可。
function greaterThan10(list)
{
for (var prop in list){
if (list[prop] > 10){
list[prop] = 0;
}
}
console.log(list)
return list;
}
此外,为了防止更复杂的对象作为参数传递,您可能需要对此进行检查。只需输入这一行:
if (!list.hasOwnProperty(prop)) continue;
在if
语句之前的for
循环内。