javascript - console.log(array) 返回填充数组,但 console.log(array.length) 为 0?

标签 javascript arrays

我在处理数组时遇到问题,但无法找到问题所在。

首先,函数在循环中执行以下两行:

varArray[overlapCounter] = [a, b, c];
overlapCounter++;

如果我运行console.log(varArray) ,chrome 日志给了我以下内容:

[]

通过打开括号,这就是内容:

Array[0]
0: Array[6]
1: Array[6]
2: Array[6]
3: Array[6]
4: Array[6]
5: Array[6]
6: Array[6]
7: Array[6]
8: Array[6]
9: Array[6]
10: Array[6]
11: Array[6]
12: Array[6]
13: Array[6]
14: Array[6]
15: Array[6]
16: Array[6]
17: Array[6]
18: Array[6]
19: Array[6]
20: Array[6]
21: Array[6]
22: Array[6]
23: Array[6]
24: Array[6]
25: Array[6]
26: Array[6]
27: Array[6]
28: Array[6]
29: Array[6]
30: Array[6]
length: 31
__proto__: Array[0]

但是如果我运行 console.log(varArray.length) ,值为0 ,和console.log(varArray[0])返回undefined .

有谁知道那里发生了什么吗?

完整代码:

$('#Salvar').click(function(e) {
          e.preventDefault();
          var dt_inicio_afastamento = $('#dt_inicio_afastamento').val();
          var dt_fim_afastamento = $('#dt_fim_afastamento').val();
          var observ_afastamento = $('#observ_afastamento').val();
          var id_ocorrencia = $('#id_ocorrencia').val();
          if ( dt_inicio_afastamento === "" || dt_fim_afastamento === "" || id_ocorrencia === ""){
            return swal({
                    title: 'Todos os campos são obrigatórios!', 
                    type: 'warning'
                });
          }
          else{
            function ajax2(names, dt_inicio_afastamento, dt_fim_afastamento, id_docente, observ_afastamento, id_ocorrencia){  
              $.ajax({
                url: '../engine/controllers/afastamento.php',
                data: {
                  id_afastamento  : null,
                  dt_inicio_afastamento : dt_inicio_afastamento,
                  dt_fim_afastamento : dt_fim_afastamento,
                  observ_afastamento : observ_afastamento,
                  id_ocorrencia : id_ocorrencia,
                  id_docente : id_docente,
                  action: 'create'
                },
                error: function() {
                  swal({ 
                      title: 'Erro na conexão com o servidor',
                      text :'Tente novamente em alguns segundos',
                      type: 'error'
                  });
                },
                success: function(data) {
                  //console.log(data);
                  if(data === 'true'){
                    names.css( "background-color", "lightgreen" );
                  }
                  else{
                   names.css( "background-color", "lightcoral" );
                  }
                }, //Sucesso Ajax2
                type: 'POST'
              }); //Ajax2
            }
            var overlapCounter = 0;
            var varArray = [];
            var requests = [];
            $(".cada_docente").each(function(index) {
              var names = $(this).prev();
              var id_docente = $(this).val();
              var nomeSerie = names.children('.nomeSerie').text();
              var requests = Array();
              (function(names, nomeSerie, dt_inicio_afastamento, dt_fim_afastamento, id_docente, observ_afastamento, id_ocorrencia){
                requests.push($.ajax({
                  url: '../engine/controllers/afastamento.php',
                  type: 'POST',
                  data: {
                    id_afastamento  : null,
                    dt_inicio_afastamento : dt_inicio_afastamento,
                    dt_fim_afastamento : dt_fim_afastamento,
                    observ_afastamento : observ_afastamento,
                    id_ocorrencia : id_ocorrencia,
                    id_docente : id_docente,
                    action: 'overlap'
                  },
                  success: function(data) {
                    if (data == "true"){ajax2(names, dt_inicio_afastamento, dt_fim_afastamento, id_docente, observ_afastamento, id_ocorrencia);}
                    else{
                        varArray[overlapCounter] = [names, dt_inicio_afastamento, dt_fim_afastamento, id_docente, observ_afastamento, id_ocorrencia];
                        overlapCounter++;
                    } 
                  } //Sucesso Ajax1
                })); //Ajax1
              })(names, nomeSerie, dt_inicio_afastamento, dt_fim_afastamento, id_docente, observ_afastamento, id_ocorrencia); //Ajax1 Função
            }); // Cada Docente
            var defer = $.when.apply($, requests);
            defer.done(function(){
                console.log(varArray);
                });


          } //Else dados colocados
        });

最佳答案

您的问题是 console.log 不能保证同步;对于像数组这样的对象引用,当您查看对象的属性树时,您将看到树当前的样子,而不是调用时的样子日志。另一方面,整数是按值传递的,因此当您 log(array.length) 时,您会在调用 log 的瞬间获得长度值。

如果您想像调用 log 时那样打印数组,您应该首先使用 array.slice() 复制它(请注意,这仅创建数组的浅拷贝):

console.log(array.slice())

关于javascript - console.log(array) 返回填充数组,但 console.log(array.length) 为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42991854/

相关文章:

php - 我需要有关如何让我的插入代码在 php 和 mysql 中工作的提示

javascript - python selenium 将键发送到只读文本框

javascript - 表格单元格条件格式

c - C中字符串数组的重新分配和新字符串的分配

javascript - 初学者 - 使用以下 While 循环时出现 "NaN"错误

javascript - 使用 Google 跟踪代码管理器自定义维度

javascript - 如何从 jQuery 中的同级 div 元素检索一些文本

Perl 数值排序 : how to ignore leading alpha character

arrays - 增加数组vba中元素的值

c - 列出数组中不重复的字符