繁体   English   中英

如何使用 javascript 从数组中删除未定义的值

[英]how to remove undefined values from array with javascript

我尝试过使用过滤器方法,但它会删除所有值。 由于这个 function,我得到了这个未定义的值。 我想合并这三个 arrays 并只删除未定义的。

示例 Arrays 值:

let arry1= ["txt", "txt2"]; 
let arry2= ["txt"]; 
let arry3= ["txt", "txt5", "txt6"]
let c =  arry1.map(function(value, index) {
        return `${value} ${arry2[index]} ${arry3[index]}` ;
      });
c =  ['txt txt txt', 'txt2 undefined undefined']

我有这个

let a = ["undefined this", "that undefined ", "undefined value undefined"]

// i want this

let a = ["this", "that", "value"]
```

Map通过数组并删除所有出现的undefined ,然后修剪结果:

 let a = ["undefined this", "that undefined ", "undefined value undefined"] const result = a.map(e => e.replaceAll("undefined", "").trim()) console.log(result)

你可以这样写

  let a=arry1.map(function(value, index) {
    value=`${value} ${arry2[index]||""}`.trim();
    return `${value} ${arry3[index]||""}`.trim() ;
  });

其他答案不区分数组元素中缺少值( undefined )与数组元素中文字字符串"undefined"

我已经解释了如何使用下面代码中的注释来适应这种情况:

 const array1 = ["txt", "txt2"]; const array2 = ["txt"]; const array3 = ["txt", "txt5", "txt6"]; // Collect the arrays into another array so that we can iterate over them: const arrays = [array1, array2, array3]; // Create an array of the lengths of the arrays: const arrayLengths = arrays.map(({length}) => length); // Get the maximum value from the lengths: const maxLength = Math.max(...arrayLengths); const result = []; // One outer loop for each index of the longest array: for (let i = 0; i < maxLength; i += 1) { // A placeholder string: let str = ''; // One inner loop for each of the arrays: for (const array of arrays) { // The value at the current index of the current array: const strOrUndefined = array[i]; // If it's actually a string, then append a space and the string // to the placeholder string: if (typeof strOrUndefined === 'string') str += ` ${strOrUndefined}`; } // Push the placeholder string into the result array, // but first remove the extra space created by the first iteration: result.push(str.trimStart()); } console.log(result); // ["txt txt txt", "txt2 txt5", "txt6"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM