我没有 JavaScript 经验。我不清楚解决这个问题的最佳方法。 我有 native javascript, 我有一个对象,我需要检查该对象的字段是否符合给定的条件。
我立即使用“IF”做了一个简单的选项
但我认为这是一个非常糟糕的决定。如何才能做得更好?
let user = {
name: 'test',
nickname: 'Doe',
age: 25,
skills: {
skill1: 'go',
skill2: 'php',
skill3: 'best of the best'
}
};
let checkField = (obj) => {
if (
typeof (obj.name) === 'string' &&
typeof (obj.nickname) === 'string' &&
obj.age >= 16 && obj.age <= 50 &&
Object.keys(obj).length > 0
) {
console.log('true')
} else {
console.log('false')
}
};
checkField(user);
条件
let user = {
name: 'test', == string
nickname: 'Doe', == string
age: 25, number in range 16..50
skills: { not empty object
skill1: 'go', == string
skill2: 'php', == string
skill3: 'best of the best' == string
}
};
最佳答案
您尝试做的事情没有任何问题,尽管根据给定的条件您错过了一些事情 -
- 检查
age
类型为number
并且 obj.skills
而不是obj
来检查它是否不为空。
这是根据条件完整更正的代码 -
let user = {
name: 'test',
nickname: 'Doe',
age: 25,
skills: {
skill1: 'go',
skill2: 'php',
skill3: 'best of the best'
}
};
let checkField = (obj) => {
if (
typeof obj.name === 'string' &&
typeof obj.nickname === 'string' &&
typeof obj.age === 'number' &&
obj.age >= 16 && obj.age <= 50 &&
obj.skills && Object.keys(obj.skills).length > 0
) {
console.log('true')
} else {
console.log('false')
}
};
checkField(user);
此外,如果您还想检查 skills
的每个属性是否都是 string
类型,您可以迭代该对象并像这样检查它 -
Object.keys(obj.skills).every(x => typeof(obj.skills[x])==='string')
关于javascript - 检查对象字段的数据是否与 native JavaScript 上的指定条件匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416453/