문제
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)
또한 모든 기능 등을 얻을 수 있지만 필요에 따라 충분할 수 있습니다.
다른 팁
내 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
제휴하지 않습니다 StackOverflow