Javascript嵌套与ES6循环 [英] Javascript Nested for loop with ES6

查看:149
本文介绍了Javascript嵌套与ES6循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我有一个嵌套的for循环,但是我想用Array map/ES6的方式来做,但是如何与嵌套的forloops一起工作呢?

I guys, I have a nested for loop but I want to do it with an Array map/ES6 way but how does that work with nested forloops?

        for (var i = 0; i < enemy.ships.length; i++) {
        for (var n = 0; n < enemy.ships[i].location.length; n++) {
            if (obj.coordination == enemy.ships[i].location[n]) hit = true;
        }
    };

当它不是forloop时,我知道该怎么做

I know how to do it when it as not a forloop

players.map(function(player){if(player.id != socket.id) return enemy = player});

但是我似乎无法理解使用数组映射或其他方法应该如何.

But I can't seem to understand how it should be with Array Maps or something else.

我需要匹配船只的位置& obj.coordination.这是我需要检查的敌人.ships变量

I need to match the location of the ships location & obj.coordination. This is the enemy.ships variable I need to check

    [ { type: 'Aircaft',
    size: 5,
    rekt: false,
    available: 1,
    location: [] },
  { type: 'Battleship',
    size: 4,
    rekt: false,
    available: 1,
    location: [ 77, 76, 75, 74 ] },
  { type: 'Destroyer',
    size: 3,
    rekt: false,
    available: 2,
    location: [ 54, 44, 34 ] },
  { type: 'Submarine',
    size: 3,
    rekt: false,
    available: 3,
    location: [] },
  { type: 'Patrolboat',
    size: 2,
    rekt: false,
    available: 4,
    location: [] } ]

推荐答案

如果您要查找的是 any 船上的 any 位置是否匹配(并且不返回,等等),您可以使用类似的命令:

If all you are looking for is whether any location on any ship matches (and not returning the ship that was hit, et cetera), you can use something like:

const hit = enemy.ships
  .map(ship => ship.location)
  .some(coordinates => coordinates.some(coordinate => coordinate === obj.coordination ));

如果您想返回被击中的飞船(或飞船,如果允许多艘飞船共享同一坐标):

If you wanted to return the ship that was hit (or the ships, if multiple ships were allowed to share the same coordinates):

const hitShips = enemy.ships
  .filter(ship => ship.location.some( coordinate => coordinate === obj.coordination ));

您的map示例也有点...关闭.

Your example of map is also a little... off.

map的目标不是引起副作用(实际上,它专门用于避免所有副作用).
map的目标是获取一个对象数组并返回完全相同长度的全新数组,在该数组中,您已基于旧数组的对象填充了新数组.

The goal of map isn't to cause side-effects (in fact, it's specifically meant to avoid all side-effects).
The goal of map is to take one array of objects and return a brand new array of the exact same length, where you have filled the new array based on the objects of the old array.

[1, 2, 3].map( x => x + 1 ); // [2, 3, 4]
["a", "b", "c"].map( x => x.toUpperCase() ); // ["A", "B", "C"]

如果您只想检查每个项目并引起副作用(更改传入的函数之外的值),请使用forEach.

If you just want to check each item and cause side-effects (change a value that exists outside of the function passed in) then use forEach.

这篇关于Javascript嵌套与ES6循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆