首页 \ 问答 \ For循环,map和forEach Javascript(For-loop, map and forEach Javascript)

For循环,map和forEach Javascript(For-loop, map and forEach Javascript)

我正在尝试创建一副52张牌。 我可以使用double for-loop轻松创建它,但它具有O(n2)复杂度。 所以我试图使用map()和forEach()数组方法,但事情很复杂,需要返回东西。 这是我的代码如下。

(function deckCreate() {
  var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
  var suits = ["clubs", "diamonds", "hearts", "spades"];
  var newDeck = values.map(function(xValue) {
    suits.forEach(function(xSuit) {
      return [xSuit,xValue];
    });
  });
  return newDeck;
}());

它给出了一个长度为13的数组,内部都是未定义的。 我尝试在map()之前交换forEach(),但结果是一样的。

我在这些函数中的console.log()时发现的问题是元素没有相互映射,而是单独打印。 可能是什么问题?


I am trying to create a deck of 52 cards. I can create it easily with double for-loop but it has O(n2) complexity. So I was trying to play with map() and forEach() array methods but things are complex with them needing to return stuffs. Here is my code below.

(function deckCreate() {
  var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
  var suits = ["clubs", "diamonds", "hearts", "spades"];
  var newDeck = values.map(function(xValue) {
    suits.forEach(function(xSuit) {
      return [xSuit,xValue];
    });
  });
  return newDeck;
}());

It gives an array of length 13 all undefined inside. I tried swapping forEach() before map() just incase but the result was the same.

The issue I found while console.log() inside those functions was that the elements were not being mapped to each other but were printed all separately. What could be the issue be?


原文:
更新时间:2022-10-15 06:10

最满意答案

master_socket被标记为可读时,您将在new_socket上调用recv() 。 假设master_socket是您的侦听服务器套接字,则需要调用accept()来接收新客户端。 除非select()告诉您特定客户端是可读的,然后从该客户端读取,否则不要调用recv()

尝试更像这样的东西:

for (i = 0; i < max_clients; ++i)
    client_socket[i] = -1;

...

while (TRUE) 
{
    FD_ZERO(&readfds);

    //add master socket to set
    FD_SET(master_socket, &readfds);
    max_sd = master_socket;

    //add child sockets to set
    for (i = 0; i < max_clients; ++i)
    {
        //socket descriptor
        sd = client_socket[i];
        if (sd > -1)
        {
            FD_SET(sd, &readfds);
            if (sd > max_sd)
                max_sd = sd;
        }
    }

    //waiting for activity
    activity = select(max_sd + 1, &readfds, NULL, NULL, NULL);
    if (activity < 0)
    {
        if (errno != EINTR)
            printf("select error");
    }
    else
    {
        //check master socket to accept from
        if (FD_ISSET(master_socket, &readfds)) 
        {
            new_socket = accept(master_socket, NULL, NULL);
            if (new_socket < 0)
            {
                printf("accept error");
            }
            else
            {
                //add new socket to array of sockets
                for (i = 0; i < max_clients; ++i)
                {
                    //if position is empty
                    if (client_socket[i] == -1)
                    {
                        client_socket[i] = new_socket;
                        printf("Adding to list of sockets as %d\n" , i);
                        send(new_socket, "here", strlen("here"), 0);
                        new_socket = -1;
                        break;
                    }
                }

                // close new socket if no room for it
                if (new_socket > -1)
                    close(new_socket);
            }
        }

        //check child sockets to read from
        for (i = 0 ; i < max_clients; ++i) 
        {
            sd = client_socket[i];
            if (sd > -1)
            {
                if (FD_ISSET(sd, &readfds)) 
                {
                    len = recv(sd, buffer, 1025, 0);
                    if (len > 0)
                    {
                        // data received
                        buffer[len] = 0; // make sure it is null terminated
                        printf("data: %s", buffer);
                        // or: printf("data: %.*s", len, buffer);
                    }
                    else
                    {
                        if (len == 0)
                            printf("disconnected");
                        else
                            printf("recv error");

                        printf("Removing from list of sockets at %d\n", i);
                        close(sd);
                        client_socket[i] = -1;
                    }
                }
            }
        }
    }

When master_socket is marked as readable, you are calling recv() on new_socket instead. Assuming master_socket is your listening server socket, you need to call accept() instead to receive a new client. Do not call recv() unless select() tells you that a specific client is readable, and then read from that client.

Try something more like this instead:

for (i = 0; i < max_clients; ++i)
    client_socket[i] = -1;

...

while (TRUE) 
{
    FD_ZERO(&readfds);

    //add master socket to set
    FD_SET(master_socket, &readfds);
    max_sd = master_socket;

    //add child sockets to set
    for (i = 0; i < max_clients; ++i)
    {
        //socket descriptor
        sd = client_socket[i];
        if (sd > -1)
        {
            FD_SET(sd, &readfds);
            if (sd > max_sd)
                max_sd = sd;
        }
    }

    //waiting for activity
    activity = select(max_sd + 1, &readfds, NULL, NULL, NULL);
    if (activity < 0)
    {
        if (errno != EINTR)
            printf("select error");
    }
    else
    {
        //check master socket to accept from
        if (FD_ISSET(master_socket, &readfds)) 
        {
            new_socket = accept(master_socket, NULL, NULL);
            if (new_socket < 0)
            {
                printf("accept error");
            }
            else
            {
                //add new socket to array of sockets
                for (i = 0; i < max_clients; ++i)
                {
                    //if position is empty
                    if (client_socket[i] == -1)
                    {
                        client_socket[i] = new_socket;
                        printf("Adding to list of sockets as %d\n" , i);
                        send(new_socket, "here", strlen("here"), 0);
                        new_socket = -1;
                        break;
                    }
                }

                // close new socket if no room for it
                if (new_socket > -1)
                    close(new_socket);
            }
        }

        //check child sockets to read from
        for (i = 0 ; i < max_clients; ++i) 
        {
            sd = client_socket[i];
            if (sd > -1)
            {
                if (FD_ISSET(sd, &readfds)) 
                {
                    len = recv(sd, buffer, 1025, 0);
                    if (len > 0)
                    {
                        // data received
                        buffer[len] = 0; // make sure it is null terminated
                        printf("data: %s", buffer);
                        // or: printf("data: %.*s", len, buffer);
                    }
                    else
                    {
                        if (len == 0)
                            printf("disconnected");
                        else
                            printf("recv error");

                        printf("Removing from list of sockets at %d\n", i);
                        close(sd);
                        client_socket[i] = -1;
                    }
                }
            }
        }
    }

相关问答

更多
  • 我已经解决了我的问题,所以我在这里发布正确的代码,以防有人需要类似的东西。 打开端口 int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY ); 设置参数 struct termios tty; struct termios tty_old; memset (&tty, 0, sizeof tty); /* Error Handling */ if ( tcgetattr ( USB, &tty ) != 0 ) { std::cout << "Erro ...
  • SQL返回行,行包含列。 JPQL有点复杂:它可以返回列的行,但也可以返回实体实例。 所以,假设你有一个(无效的)JPQL查询 select * from School school join school.students student where ... 查询应该返回什么? 学校的实例? 学生实例? 列? 很难知道。 假设它返回学校和学生的所有领域,这些领域的顺序是什么? 你怎么能用这个结果? 如果你这样做的话 select school from School school join school ...
  • 如果你切换到fscanf你可以使用int而不是char,并且鉴于你正在解析包含数字的文本文件,它更有意义。 假设您的100.txt有一个由空格分隔的100个数字,这应该有效: int main(int argc, char* argv[]) { FILE* file; char name[10] = "100.txt"; char line[10]; int n; int numberArray[100]; file = fopen(name, "rt"); ...
  • 以下应该工作,可能存在拼写错误,但该过程应该是有效的。 using (StreamWriter sw = new StreamWriter("C:\\Temp\\Test.txt")) { DataSet ds = GetData(); //call sproc, return data foreach(DataRow dr in ds.Rows) { var column = string.IsNullOrEmpty((dr["MemoCol ...
  • select b.title, t.tag from books b inner join books_tags bt on b.id = bt.book_id inner join tags t on bt.tag_id = t.id order by b.title, t.tag 如果您想列出没有标签的书籍,您可以这样做: select b.title, t.tag from books b left outer join books_tags bt on b.id = bt.book_id left ...
  • 代替: var ent = conn.Query("SELECT SUM(price) FROM Transaction WHERE price > 0"); 使用: var ent = conn.ExecuteScalar ("SELECT SUM(price) FROM Transaction WHERE price > 0"); ExecuteScalar用于从数据库返回标量值。 Instead of: var ent = conn.Query
  • 是的,通常的做法是为每个客户端设置一个“我已收到但未处理的数据”的缓冲区,其大小足以容纳最大的协议消息。 您读入该缓冲区(始终跟踪缓冲区中当前有多少数据),并且在每次读取之后,检查是否有完整的消息(或消息,因为您可能一次获得两个消息!)。 。 如果这样做,则处理该消息,将其从缓冲区中移除,并将剩余的数据移至缓冲区的起始位置。 大致沿着以下方向的东西: for (i = 0; i < nclients; i++) { if (!FD_ISSET(client[i].fd, &read_fds)) ...
  • 当master_socket被标记为可读时,您将在new_socket上调用recv() 。 假设master_socket是您的侦听服务器套接字,则需要调用accept()来接收新客户端。 除非select()告诉您特定客户端是可读的,然后从该客户端读取,否则不要调用recv() 。 尝试更像这样的东西: for (i = 0; i < max_clients; ++i) client_socket[i] = -1; ... while (TRUE) { FD_ZERO(&readf ...
  • 不要忘记在重新打开文件之前关闭文件,即使您从读/写切换。 干得好: using namespace std; int main() { ofstream age; age.open("age.txt", ios::out); cout << "Input the ages from keyboard: " << endl; for (int i = 0;i<3;i++) { int n; cin >> n; //val ...
  • 您需要使用此语法。 SELECT id, first_name, last_name AS [Full Name] FROM name; 单引号用于表示字符串。 方括号应该用于包含空格的字段名称。 You need to use this syntax. SELECT id, first_name, last_name AS [Full Name] FROM name; Single quotes are used to denote strings. Square brackets should be ...

相关文章

更多

最新问答

更多
  • sp_updatestats是否导致SQL Server 2005中无法访问表?(Does sp_updatestats cause tables to be inaccessible in SQL Server 2005?)
  • 如何创建一个可以与持续运行的服务交互的CLI,类似于MySQL的shell?(How to create a CLI that can interact with a continuously running service, similar to MySQL's shell?)
  • AESGCM解密失败的MAC(AESGCM decryption failing with MAC)
  • Zurb Foundation 4 - 嵌套网格对齐问题(Zurb Foundation 4 - Nested grid alignment issues)
  • 湖北京山哪里有修平板计算机的
  • SimplePie问题(SimplePie Problem)
  • 在不同的任务中,我们可以同时使用多少“上下文”?(How many 'context' we can use at a time simultaneously in different tasks?)
  • HTML / Javascript:从子目录启用文件夹访问(HTML/Javascript: Enabling folder access from a subdirectory)
  • 为什么我会收到链接错误?(Why do I get a linker error?)
  • 如何正确定义析构函数(How to properly define destructor)
  • 垂直切换菜单打开第3级父级。(Vertical toggle menu 3rd level parent stay opened. jQuery)
  • 类型不匹配 - JavaScript(Type mismatch - JavaScript)
  • 为什么当我将模型传递给我的.Net MVC 4控制器操作时,它坚持在部分更新中使用它?(Why is it that when I pass a Model to my .Net MVC 4 Controller Action it insists on using it in the Partial Update?)
  • 在使用熊猫和statsmodels时拉取变量名称(Pulling variable names when using pandas and statsmodels)
  • 如何开启mysql计划事件
  • 检查数组的总和是否大于最大数,反之亦然javascript(checking if sum of array is greater than max number and vice versa javascript)
  • 使用OpenGL ES绘制轮廓(Drawing Outline with OpenGL ES)
  • java日历格式(java Calendar format)
  • Python PANDAS:将pandas / numpy转换为dask数据框/数组(Python PANDAS: Converting from pandas/numpy to dask dataframe/array)
  • 如何搜索附加在elasticsearch索引中的文档的内容(How to search a content of a document attached in elasticsearch index)
  • LinQ to Entities:做相反的查询(LinQ to Entities: Doing the opposite query)
  • 从ExtJs 4.1商店中删除记录时会触发哪些事件(Which events get fired when a record is removed from ExtJs 4.1 store)
  • 运行javascript后如何截取网页截图[关闭](How to take screenshot of a webpage after running javascript [closed])
  • 如何使用GlassFish打印完整的堆栈跟踪?(How can I print the full stack trace with GlassFish?)
  • 如何获取某个exe应用程序的出站HTTP请求?(how to get the outbound HTTP request of a certain exe application?)
  • 嗨,Android重叠背景片段和膨胀异常(Hi, Android overlapping background fragment and inflate exception)
  • Assimp详细说明typedef(Assimp elaborated type refers to typedef)
  • 初始化继承类中不同对象的列表(initialize list of different objects in inherited class)
  • 使用jquery ajax在gridview行中保存星级评分(Save star rating in a gridview row using jquery ajax)
  • Geoxml3 groundOverlay zIndex(Geoxml3 groundOverlay zIndex)