gpt4 book ai didi

带有对象键的 JavaScript setter 和 getter

转载 作者:行者123 更新时间:2023-11-28 11:24:35 25 4
gpt4 key购买 nike

我在变量中有一个对象 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

关于带有对象键的 JavaScript setter 和 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18549775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com