我有一个遍历object属性的代码实现。
for (const prop in obj) {
propsMap[prop] = prop;
}但正如我所说的那样,我的集成开发环境(WebStorm)建议我使用obj.hasOwnProperty(prop)添加一个属性检查,以避免迭代不存在的属性:
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
propsMap[prop] = prop;
}
}问题是,当前的测试总是带有obj.hasOwnProperty(prop)为true,覆盖率并不是我能得到的最好的,我不知道如果obj实际上没有prop属性会发生什么。
发布于 2017-08-10 14:45:08
要测试这一点,您可以创建继承其原型的对象
const obj = Object.create({name: 'inherited'})name将伪造obj.hasOwnProperty('name')检查。
但是有更好的选择来复制对象。例如Object.assign
Object.assign(propsMap, obj)此外,您还应该记住,obj.hasOwnProperty检查很容易出错。例如
const obj = {hasOwnProperty: null} // hasOwnProperty is not a function
const obj = Object.create(null) // obj wont inherit hasOwnProperty 所以至少将它替换为
const hasOwnProperty = {}.hasOwnProperty
for(const name in obj) {
if(hasOwnProperty.call(obj, name)) {
}https://stackoverflow.com/questions/45606054
复制相似问题