문제

JavaScript에서 해시 테이블을 사용하고 있으며 해시 테이블에 다음 값을 표시하고 싶습니다.

one   -[1,10,5]
two   -[2]
three -[3, 30, 300, etc.]

다음 코드를 찾았습니다. 다음 데이터에 대해 작동합니다.

   one  -[1]
   two  -[2]
   three-[3]

해시 테이블에 하나의 [1,2] 값을 어떻게 할당합니까? 어떻게 액세스합니까?

<script type="text/javascript">
    function Hash()
    {
        this.length = 0;
        this.items = new Array();
        for (var i = 0; i < arguments.length; i += 2) {
            if (typeof(arguments[i + 1]) != 'undefined') {
                this.items[arguments[i]] = arguments[i + 1];
                this.length++;
            }
        }

        this.removeItem = function(in_key)
        {
            var tmp_value;
            if (typeof(this.items[in_key]) != 'undefined') {
                this.length--;
                var tmp_value = this.items[in_key];
                delete this.items[in_key];
            }
            return tmp_value;
        }

        this.getItem = function(in_key) {
            return this.items[in_key];
        }

        this.setItem = function(in_key, in_value)
        {
            if (typeof(in_value) != 'undefined') {
                if (typeof(this.items[in_key]) == 'undefined') {
                    this.length++;
                }

                this.items[in_key] = in_value;
            }
            return in_value;
        }

        this.hasItem = function(in_key)
        {
            return typeof(this.items[in_key]) != 'undefined';
        }
    }

    var myHash = new Hash('one',1,'two', 2, 'three',3 );

    for (var i in myHash.items) {
        alert('key is: ' + i + ', value is: ' + myHash.items[i]);
    }
</script>

어떻게해야하나요?

도움이 되었습니까?

해결책

위의 기능을 사용하면 다음을 수행 할 수 있습니다.

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);

물론 다음도 효과가있을 것입니다.

var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];

JavaScript의 모든 객체는 해시 테이블이므로! 그러나 사용한 이후로 반복하기가 더 어려울 것입니다. foreach(var item in object) 또한 모든 기능 등을 얻을 수 있지만 필요에 따라 충분할 수 있습니다.

다른 팁

정적 값을 조회 테이블에 저장하는 것만으로도 물체 문자 그대로 (동일한 형식이 사용했습니다 JSON) 소형을 수행하려면 :

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }

그런 다음 JavaScript의 연관 배열 구문을 사용하여 액세스하십시오.

alert(table['one']);    // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10

내 JavaScript 해시 테이블 구현을 사용할 수 있습니다. jshashtable. 그것은 문자열뿐만 아니라 모든 객체를 키로 사용할 수 있습니다.

JavaScript 통역사는 기본적으로 객체를 해시 테이블에 저장합니다. 프로토 타입 체인의 오염이 걱정된다면 항상 다음과 같은 일을 할 수 있습니다.

// Simple ECMA5 hash table
Hash = function(oSource){
  for(sKey in oSource) if(Object.prototype.hasOwnProperty.call(oSource, sKey)) this[sKey] = oSource[sKey];
};
Hash.prototype = Object.create(null);

var oHash = new Hash({foo: 'bar'});
oHash.foo === 'bar'; // true
oHash['foo'] === 'bar'; // true
oHash['meow'] = 'another prop'; // true
oHash.hasOwnProperty === undefined; // true
Object.keys(oHash); // ['foo', 'meow']
oHash instanceof Hash; // true
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top