【发布时间】:2022-06-17 17:35:15
【问题描述】:
您的函数应该接收一个对象作为其唯一参数,并返回一个具有相同属性但添加了类型验证的对象。应在以下情况下验证类型:
- 函数创建对象;
- 有人更新了属性;
- 有人添加了属性;
类型验证应始终基于属性名称的最后一部分。例如,age_int 属性应始终为整数,并在设置为其他值时抛出错误
以下是可能的类型:
- 字符串:例如“字符串类型”
- int:12.00 和 12 都是整数。
- 浮点数:例如,12.34
- 数字:任何整数或浮点数
- bool:例如,true
假设
- 类型是可选的,如果未指定类型,则应跳过验证。
- 始终位于类型名称之前。
示例
你的函数应该如下所示:
const obj= {
age_int: 2,
name_string:"John",
Job: null,
}
const validatingbject=typeCheck(obj)
validatingobject.age_int=2.25 // Throws error
validatingbject.age.int= 2
validatingoject.job="fireman"
validatingbject.address_string= 20 // Throws error
const obj_2= {employed_bool: "true",}
const validatingobject = typeCheck(obj_2) // Throws error
我尝试了下面的代码,但没有成功。
function typeCheck(object) {
console.log(Object.entries(object));
Object.entries(object).forEach(([key, value]) => {
let type = key.split('_').pop();
let typecheck;
console.log("type:", type);
if (type === "float" || type === "int" || type === "number") {
typecheck = "number";
} else if (type === "bool") {
typecheck = "boolean";
} else if (type === "string") {
typecheck = "string";
}
if (typeof value == typecheck) {
return true;
} else {
console.error("error")
}
});
}
const obj = {
age_int: 2,
name_string: "John",
Job: null,
}
const validatingbject = typeCheck(obj);
【问题讨论】:
标签: javascript javascript-objects