在javascript中设置对象

在javascript中设置对象

本文介绍了在javascript中设置对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Javascript中有一组对象。也就是说,一个仅包含唯一对象的数据结构。



建议使用属性。 myset [key] = true 。但是,我需要的键是对象。我已经看到Javascript将属性名称转换为字符串,所以我想我不能使用 myset [myobject] = true



我可以使用数组,但是我需要比O(n)性能更好的添加,查找和删除项目。



它需要能够通过参考来分开对象,所以给出:

  var a = {}; 
var b = {};

然后两者 a b 应该可以添加,因为它们是单独的对象。



基本上,我的东西像C ++的code> std :: set ,可以存储Javascript对象。任何想法?

解决方案

ES6提供了一个本地地图

  let m = new Map(); 
let a = {};
let b = {};

m.set(a,b);
m.set(b,10);

m.get(m.get(a))// 10

这是一个很久以前我已经有一个接近自然的结构,你可以得到:

 功能映射( ){
var keys = [];
var values = [];

函数get(key){
var i = keys.indexOf(key);
return i === -1? null:values [i];
}

get.set =函数集(key,value){
var i = keys.indexOf(key);

if(i === -1){
keys.push(key);
values.push(value);
} else {
values [i] = value;
}
};

return get;
}

使用它像这样:

  var m = map(); 
var a = {};
var b = {};

m.set(a,b);
m.set(b,10);

m(m(a)); // 10

要删除一个值,只需使用 x.set(whateverKey ,null)因为它没有找到钥匙时返回null,所以没有区别。


I'd like to have a set of objects in Javascript. That is, a data structure that contains only unique objects.

Normally using properties is recommended, e.g. myset["key"] = true. However, I need the keys to be objects. I've read that Javascript casts property names to strings, so I guess I can't use myset[myobject] = true.

I could use an array, but I need something better than O(n) performance for adding, finding and removing items.

It needs to be able to tell objects apart by reference only, so given:

var a = {};
var b = {};

then both a and b should be able to be added, because they're separate objects.

Basically, I'm after something like C++'s std::set, that can store Javascript objects. Any ideas?

解决方案

ES6 provides a native Map:

let m = new Map();
let a = {};
let b = {};

m.set(a, b);
m.set(b, 10);

m.get(m.get(a))  // 10

Here's one I have from a long time ago that is about as close to natural structure as you can get:

function map() {
    var keys = [];
    var values = [];

    function get(key) {
        var i = keys.indexOf(key);
        return i === -1 ? null : values[i];
    }

    get.set = function set(key, value) {
        var i = keys.indexOf(key);

        if (i === -1) {
            keys.push(key);
            values.push(value);
        } else {
            values[i] = value;
        }
    };

    return get;
}

Use it like so:

var m = map();
var a = {};
var b = {};

m.set(a, b);
m.set(b, 10);

m(m(a));  // 10

To remove a value, just use x.set(whateverKey, null) because it returns null when the key is not found so there is no difference.

这篇关于在javascript中设置对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:22