【问题标题】:Getting Undefined values even with if statement即使使用 if 语句也能获得未定义的值
【发布时间】:2020-04-10 22:56:21
【问题描述】:

我将值推送到 forEach 循环内的数组中。当我在循环外调用数组时,我得到了这些值:

d.data:

[{hello: 'abc', asd: '123', fgh: '345' }]
[{sdfg: '123', yo: 'ghj', fgh: '345' }]
[{gd: '123', asd: '123', bonjour: 'yui' }]
[{hello: '123', asd: '567', fgh: '345' }]

forEach 循环:

let str_arr = [];
d.data.forEach(recs => {
  each_keys = Object.keys(recs);
  each_vals = Object.values(recs);
  each_vals.forEach(k => {
    if (typeof k == 'string') {
        find_key = Object.keys(recs).find(key => recs[key] === k);
        str_arr.push(find_key);
    } 
   });
});

str_arr:

["hello", "hello", "hello"]
["yo", "yo", "yo"]
["bonjour", "bonjour", "bonjour"]
[]

console.log(typeof str_arr[0] + ' = ' + str_arr[0]

结果:

string = hello
string = yo
string = bonjour
undefined = undefined

我想将所有 str_arr[0] 推入一个数组,所以我这样做?

let string_array = [];
if (str_arr[0] !== undefined) {
    string_array.push(str_arr[0]);
}
console.log(string_array);

我的结果是:

hello
yo
string
     (empty)

为什么我的结果中仍然出现未定义的值?

【问题讨论】:

  • 可以分享array的内容吗?
  • @ManuelAbascal,你在说 str_arr 吗?
  • 我认为你需要展示整个代码示例才有意义。
  • 您能否发布更多显示整个过程的代码,包括 for 循环?
  • 我同意您需要发布一个可以执行的示例。但顺便说一句,您可能需要考虑使用 .filter() developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 而不是像您正在做的那样循环和推送。

标签: javascript jquery arrays json undefined


【解决方案1】:

input_arr = [
  ["hello", "hello", "hello"],
  ["yo", "yo", "yo"],
  ["bonjour", "bonjour", "bonjour"],
  []
];
let output_array = [];
input_arr.forEach(element => {
  if (element[0] !== undefined) {
    output_array.push(element[0]);
  }
});
console.log(output_array);
console.log(input_arr[3][0] !== undefined); // works as expected

【讨论】:

    【解决方案2】:

    // Results from the forEach loop
    var str_arr = 
    [
      ["hello", "hello", "hello"], 
      ["yo", "yo", "yo"],
      ["bonjour", "bonjour", "bonjour"],
      []
    ];
    
    let string_array = []; 
    
    str_arr.forEach(
      function (item_arr)
      {
        if (item_arr[0] !== undefined || item_arr)
        {
          string_array.push(item_arr[0]);
        }
      }
    );
    
    // Here's your answer
    console.log(string_array);

    【讨论】:

      【解决方案3】:

      在您的帖子中,您声明:

      d.data:

      [{hello: 'abc', asd: '123', fgh: '345' }]
      [{sdfg: '123', yo: 'ghj', fgh: '345' }]
      [{gd: '123', asd: '123', bonjour: 'yui' }]
      [{hello: '123', asd: '567', fgh: '345' }]
      

      这没有意义,因为这将是 4 个唯一数组,使 data 成为数组数组(其中包含对象)。这将如下所示。

      d.data = [
        [{hello: 'abc', asd: '123', fgh: '345' }],
        [{sdfg: '123', yo: 'ghj', fgh: '345' }],
        [{gd: '123', asd: '123', bonjour: 'yui' }],
        [{hello: '123', asd: '567', fgh: '345' }]
      ];
      

      或者它应该是一个对象数组,表示为:

      d.data = [
        {hello: 'abc', asd: '123', fgh: '345' },
        {sdfg: '123', yo: 'ghj', fgh: '345' },
        {gd: '123', asd: '123', bonjour: 'yui' },
        {hello: '123', asd: '567', fgh: '345' }
      ];
      

      我也无法确定您的意思是让包含数字的字符串在对象中是整数还是字符串。您似乎在 if() 中寻找字符串,但它们的存储方式,它们都是字符串。

      假设后者,并且它们可能需要被视为数字而不是字符串,我建议使用 $.each()parseInt()

      $(function() {
        var d = {
          data: [{
              hello: 'abc',
              asd: '123',
              fgh: '345'
            },
            {
              sdfg: '123',
              yo: 'ghj',
              fgh: '345'
            },
            {
              gd: '123',
              asd: '123',
              bonjour: 'yui'
            },
            {
              hello: '123',
              asd: '567',
              fgh: '345'
            }
          ]
        };
        var str_arr = [];
      
        $.each(d.data, function(i, el) {
          console.log(i, el);
          $.each(el, function(k, v) {
            console.log(k + ": " + v);
            if (!(parseInt(v))) {
              console.log("Found String: " + k);
              str_arr.push(k);
            }
          });
        });
      
        console.log(str_arr.join(", "));
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

      这里我们迭代数组中的每个元素(i = 数组索引,el = 数组元素)。由于元素是一个对象,因此我们嵌套了第二个循环来迭代对象(k = 对象键,v = 对象值)。

      现在我们可以测试Value并将Key存储在str_arr中,如果它满足条件。我认为这就是你试图用你的代码做的事情。真的不确定。

      你也可以看看使用.map().filter() 他们都可以做到这一点。也许行数更少。

      【讨论】:

        猜你喜欢
        • 2020-02-27
        • 1970-01-01
        • 1970-01-01
        • 2013-10-14
        • 1970-01-01
        • 2020-04-12
        • 2020-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多