简体   繁体   English

Javascript setter和getter与对象的键

[英]Javascript setter and getter with key for object

I have an object in a variable var o={}; 我在变量var o={};有一个对象var o={}; I want to do something like what .push() method doing in array for my object. 我想为我的对象做类似.push()方法的事情。

JS code: JS代码:

// Array:
var ar=[];
ar.push('omid');
ar.push('F');
var got=ar[1];
// above code is standard but not what I'm looking for !
/*-------------------------------------*/


// Object:
var obj={};

/*  obj.push('key','value'); // I want do something like this
    var got2=obj.getVal('key'); // And this
*/

Is this possible at all ? 这有可能吗?

var obj = {}

// use this if you are hardcoding the key names
obj.key = 'value'
obj.key // => 'value'

// use this if you have strings with the key names in them
obj['key2'] = 'value'
obj['key2'] // => 'value'

// also use the second method if you have keys with odd names
obj.! = 'value' // => SyntaxError
obj['!'] = 'value' // => OK

Since Object-Literals use a Key->Value model, there is no JS method to "push" a value. 由于Object-Literals使用Key->Value模型,因此没有JS 方法可以“推送”值。

You can either use Dot Notation: 您可以使用点表示法:

var Obj = {};

Obj.foo = "bar";

console.log(Obj);

Or Bracket Notation: 或括号符号:

var Obj = {},
    foo = "foo";

Obj[foo]   = "bar";
Obj["bar"] = "foo";

console.log(Obj);

Consider reading https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects , as arming yourself with this knowledge will be invaluable in the future. 考虑阅读https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Working_with_Objects ,因为将来掌握这些知识将非常宝贵。

Here is some javascript magic that makes it work. 这是使它起作用的一些JavaScript魔术。 Take a look. 看一看。

var obj = {};
Object.defineProperty(obj,'push',{
 value:function(x,y){
  this[x]=y;
 }
});

obj.push('name','whattttt');  <<<this works!!!

obj;
//{name:'whattttt'}
obj.name or obj['name']..
//whattttt

The reason i defined .push function using Object.defineProperty because i didn't want it to show up as a property of object. 之所以使用Object.defineProperty定义.push函数,是因为我不希望它显示为对象的属性。 So if you have 3 items in object this would have always been the 4th one. 因此,如果您有3件物品,那么该物品将永远是第4件。 And mess up the loops always. 并且总是弄乱循环。 However, using this method. 但是,使用此方法。 You can make properties hidden but accessible. 您可以使属性隐藏但可以访问。

Though i don't know why you would use this method when there is already a easy way to do it. 尽管我不知道为什么已经有一种简单的方法可以使用这种方法。

to assign a value do this 分配一个值

obj.variable = 'value';

if value key is number or weird do this... 如果值键是数字或很奇怪,请执行此操作...

obj[1] = 'yes';

to access number or weird name you also do that 要访问号码或奇怪的名字,您也可以这样做

obj[1];

and finally to assign random keys or key that has been generated in code, not hard coded, than use this form too. 最后,分配随机密钥或已在代码中生成的(不是硬编码的)密钥也要使用此格式。

var person= 'him';

obj[him]='hello';

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

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