JSON can be said to be the highlight of JavaScript. It can implement the initialization of Object and Array with elegant and concise code. It is also a text-based data definition, which is more semantic than symbol separation and more concise than XML. Therefore, more and more JS developers use it as data transmission and storage.
JS arrays have many useful methods built-in to facilitate our query and filtering of data. For example, we have a bunch of data:
var heroes = [
// Name============Attack======Defense========Strength====Dexterity=====Intelligence====
name: 'Ice Room Witch', DP: 38, AP: 1.3, STR: 16, AGI: 16, int: 21},
{name: 'Silent Warlock', DP: 39, AP: 1.1, STR: 17, Agi:16, Int:21},
{name:'Naga Siren', DP:51, AP:6.0, Str:21, Agi:21, Int:18},
{name :'Bounty Hunter', DP:39, AP:4.0, Str:17, Agi:21, Int:16},
18, Agi:22, Int:15},
{name:'Guardian of Light', DP:38, AP:1.1, Str:16, Agi:15, Int:22},
{name: 'Alchemist', DP:49, AP:0.6, Str:25, Agi:11, Int:25}
For heroes whose defense is greater than 40 and whose defense is less than 4, we can use Array’s filter method:
Copy code
Compared with manually writing loop judgments, the filter method provides us with great convenience. But it is based on function callbacks, so you must write a function every time you use it, which is very cumbersome for simple queries, and the efficiency of using callbacks is also greatly reduced. But there is no way to do this. If you want to be simple, you must sacrifice a certain amount of performance. How perfect it would be if we could use simpler statements than this and fully enjoy the efficiency of code expansion.
First imagine, if the above code can be written like this, and
the query speed is the same as the handwritten traversal judgment
:
Copy the code
The code is as follows: