简体   繁体   English

从javascript对象中删除属性的函数

[英]Function to delete a property from object in javascript

I want to write a function which will return true if property of the object is deleted and for others it should return me false.The function accepts two parameters, object and the property name.This can be more clear withe the below code:- 我想编写一个函数,如果删除了对象的属性,它将返回true;对于其他对象,它应该返回false;该函数接受两个参数,对象和属性名称。使用下面的代码可以更清楚地看到它:

 var removeObjectProp = function(obj, propName) { if (obj.hasOwnProperty(propName)) { return delete obj.propName; } return false; } var emp = { name: 'jack', age: 12 }; console.log(removeObjectProp(emp, 'name')); console.log(emp) 

output: 输出:

    True
    {name: "jack", age: 12}
    age:12
    name:"jack"
    __proto__:
    Object
   }

So again I am getting the same object.If I modify the function:- 所以我再次得到相同的对象。如果我修改功能:-

 var removeObjectProp = function(obj, propName){
         return delete obj.propName;
    } 

and call the 并致电

console.log(removeObjectProp (emp,'salary'));

Always it is returning true. 总是返回真。 How can i write the function to delete the property of an object passed as parameter? 如何编写函数以删除作为参数传递的对象的属性?

In order to delete a property, if the property name is a string you have in a variable, you need to use bracket notation to delete the property: 为了delete属性,如果属性名称是变量中包含的字符串,则需要使用方括号符号来删除属性:

return delete obj[propName];

You would use 你会用

delete obj.propName;

only when propName was the literal name of the property, eg with 仅当propName是属性的文字名称时,例如

{ name: 'jack', propName: 'foo' }

 var removeObjectProp = function(obj, propName) { if (obj.hasOwnProperty(propName)) { return delete obj[propName]; } return false; } var emp = { name: 'jack', age: 12 }; console.log(removeObjectProp(emp, 'name')); console.log(removeObjectProp(emp, 'propThatDoesNotExist')); console.log(emp) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM