【问题标题】:empty elements in arrays are not evaluated to undefined? [duplicate]数组中的空元素不会被评估为未定义? [复制]
【发布时间】:2021-06-18 07:26:48
【问题描述】:

我的目标是检查整数数组中是否有空值> 0:

给定 const array = [1, 4, , 7, 14] 我希望测试返回 false。你可以得到那个结果,即通过!array.includes(undefined)

但如果我使用函数array.every(el => el !== undefined),它的计算结果是否为真? 那么js数组中的空元素是未定义还是完全不同的数据类型?

【问题讨论】:

标签: javascript arrays types


【解决方案1】:

使用Object.getOwnPropertyNames()Array.prototype.slice()

const array1 = [1, 4, , 7, 14],
  array2 = [1, 2, 3, 4],
  res = (array) =>
    Object.getOwnPropertyNames(array).slice(0, -1).length === array.length
      ? "No Empty"
      : "Yes Empty";
console.log(res(array1));
console.log(res(array2));

【讨论】:

    【解决方案2】:

    “旧式”数组迭代器(forEach 和朋友)不会迭代数组中实际不存在的索引(“洞”):

    a = [0, 1, , 3, 4]
    a.forEach(x => console.log(x))

    (将此与“新样式”迭代器进行比较):

    a = [0, 1, , 3, 4]
    for (let x of a)
        console.log(x)

    检测空洞的一种方法是在数组上运行计数旧式迭代器并将结果与​​其长度进行比较:

    a = [0, 1, , 3, 4]
    let count = a => a.reduce(c => c + 1, 0);
    console.log(count(a) < a.length) // true -> has holes

    如果您尝试检测 任何 未定义值,包括孔洞和“物化”未定义值,请使用“新样式”展开来获取所有值的列表并应用 some 或 @ 987654326@:

    a = [0, 1, , 2, 4]
    console.log([...a].some(x => x === undefined))
    
    
    a = [0, 1, undefined, 2, 4]
    console.log([...a].some(x => x === undefined))

    【讨论】:

    • 我不知道新旧之间的这种区别,很好的解释!
    猜你喜欢
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多