Java脚本对象处理



如果一个对象键中有int,那么在JavaScript中该值必须是整数,我们能限制吗?

let myData {
dob_int: 1990
}
myData.dob_int = "a"; //need to be throw error

您可以创建这样的setter。如果值正确,则调用setter设置"dob_Int"。

let myData = {
set dobInt(value){
if(!isNaN(value)){
console.log('Is Valid')
this.dob_int = value
} else {
console.log('Is not Valid')
}
}
}
myData.dobInt = 'A'
//will log 'Is not Valid' and will not update the object key value
myData.dobInt = 5
//will log 'Is Valid' and will set dob_int to the value

最新更新