 ## Using objects as array keys | |
[ 所属分类 前端（javascript） | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏
In setting up ourAmazing Maze Game we created an object Position{x, y} to store the position of the hero in the maze, and a 2-dimensional array maze[x][y] representing the maze grid, but this led to some awkward coding which would be simplified if our Position object could be used as an array index. Defining the problem

Consider the following simple javascript object:

function Position(x, y) { this.x = x; this.y = y; }

We can now assign a position to our hero using:

var heroPos = new Position(2, 2);

and if we define our maze grid as:

/* [1, 2, 3], [4, 5, 6], [7, 8, 9] /* var maze = []; maze = 1; meze = 2; meze = 3; meze = 4; ... maze = 9; // <-- heroPos

this places the hero in the bottom right corner where the value is nine.

Only to actually get the value of that grid position in the maze we have to use:

maze[heroPos.x][heroPos.y]; // maze == 9

What we'd like to be able to use instead is:

maze[heroPos]; // maze[Position{2,2}] == 9 Why can't objects be keys

To set up our maze using Position objects as keys we use something like the following:

var maze = []; maze[new Position(0, 0)] = 1; maze[new Position(0, 1)] = 2; maze[new Position(0, 2)] = 3; maze[new Position(1, 0)] = 4; ... maze[new Position(2, 2)] = 9; // <-- heroPos

But this doesn't work as expected as we end up with only a single array value:

for(var x in maze) { console.log(x + " => " + maze[x]); } [object Object] => 9 What's happening? It turns out that when you try to use an object as an array key the objects toString() method is invoked, which by default returns the string "[object Object]" regardless of the object attribute values. How to make it work

It turns out there's a very simple solution. Knowing that the objects toString() method is going to be invoked we just have to overwrite it with our own:

function Position(x, y) { this.x = x; this.y = y; } Position.prototype.toString = function() { return this.x + ":" + this.y; }; Now when we populate our maze as before, instead of the "[object Object]" we see our new custom values for the whole 3×3 grid: for(var x in maze) { console.log(x + " => " + maze[x]); } 0:0 => 1 0:1 => 2 0:2 => 3 1:0 => 4 ... 2:2 => 9

And we can now use the desired syntax:

maze[heroPos]; // maze["2:2"] == 9

To see the code in action check out ourAmazing maze game with source code.

< JavaScript

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。 技术大类 | 前端（javascript） | 评论(0) | 阅读(25)