首页 > 解决方案 > 请告诉我,如何创建一个将对象的所有数字属性乘以 2 的函数

问题描述

创建一个函数 multiplyNumeric(objectExample) 将 objectExample 的所有数字属性乘以 2。我的错误在哪里?

let objectExample = {
    width: 200,
    height: 300,
    title: 'example'
}

let multiplyNumeric = (key, object) => {
    for (let key in object) {
        if (typeof object.key === 'number') {
            object.key *= 2;
        }
    }
}

multiplyNumeric(objectExample);

console.log(objectExample);


非常感谢您。

标签: javascriptobject

解决方案


let objectExample = {
  width: 200,
  height: 300,
  title: 'example'
}

let multiplyNumeric = obj => {
  for (let [key, value] of Object.entries(obj)) {
    if (typeof value === 'number') {
      obj[key] = value * 2;
    }
  }
}

multiplyNumeric(objectExample);
console.log(objectExample);


推荐阅读