带有对象键的Javascript setter和getter

Javascript setter and getter with key for object

本文关键字:setter getter Javascript 对象      更新时间:2023-09-26

我在变量var o={};中有一个对象我想为我的对象做一些类似于.push()方法在数组中所做的事情。

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
*/

这可能吗?

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

由于Object Literals使用Key->Value模型,因此没有JS方法来"推送"值。

您可以使用点符号:

var Obj = {};
Obj.foo = "bar";
console.log(Obj);

或括号符号:

var Obj = {},
    foo = "foo";
Obj[foo]   = "bar";
Obj["bar"] = "foo";
console.log(Obj);

考虑阅读https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects,因为用这些知识武装自己在未来将是非常宝贵的。

以下是一些让它发挥作用的javascript魔法。看一看。

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

我使用Object.defineProperty定义.prush函数的原因是我不希望它显示为对象的属性。所以,如果对象中有3个项目,这将一直是第4个。而且总是把循环弄得一团糟。但是,使用这种方法。您可以使属性隐藏但可访问。

虽然我不知道为什么你会使用这种方法,因为已经有了一种简单的方法。

要分配值,请执行此

obj.variable = 'value';

如果值键是数字或怪异,请执行此操作。。。

obj[1] = 'yes';

要访问号码或奇怪的名字,你也可以使用

obj[1];

最后分配随机密钥或在代码中生成的密钥,而不是硬编码的,也可以使用这种形式。

var person= 'him';
obj[him]='hello';