【问题标题】:The length of an item of an array should be undefined however in debugger it has a value数组项的长度应该是未定义的,但是在调试器中它有一个值
【发布时间】:2020-06-05 15:21:30
【问题描述】:

这是一种将数组细分为更小块的解决方案。该解决方案在数组项上使用长度属性,这对我来说没有意义,因为它应该是未定义的;但是,该解决方案确实有效,当我在带有调试器的 chrome 开发工具中将它作为 sn-p 运行时,它确实显示了一个值,我只是不确定它是如何工作的。我无法解释为什么last.length 有任何价值。有人可以解释为什么这有效,以及为什么我不能 console.log 为它记录一个值吗?

const chunk = (arr, size) => {
    let newArr = []
    for (let el of arr) {
        let last = newArr[newArr.length -1]
        console.log(last, 'i am last')
        if(!last || last.length === size) {
            newArr.push([el])
        } else {
            last.push(el)
        }
    } 
    return newArr
}

// chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]

【问题讨论】:

  • 因为last 是一个数组(因为数组中的项目是数组)?数组有一个 .length ?
  • 我认为他指的是let last = newArr[newArr.length -1] 将导致undefined 被分配到最后。

标签: javascript arrays algorithm for-loop


【解决方案1】:

您可以将last 的声明移到循环之外,并阻止每个项目对newArr 的新访问。

const chunk = (arr, size) => {
    let newArr = [];
    let last;
    for (let el of arr) {
        if (!last || last.length === size) {
            last = [];
            newArr.push(last);
        }
        last.push(el);
    } 
    return newArr
}

console.log(chunk([1, 2, 3, 4, 5], 2));

【讨论】:

    【解决方案2】:

    TLDR:当last未定义时,这个表达式

    (!last || last.length === size)
    

    仍然评估为真。继续阅读以了解更多详情。

    在循环的第一次迭代中,发生了这个赋值:

    let last = newArr[-1];
    

    因此,last 被赋值为 undefined

    后续声明:

    if(!last || last.length === size) {
    

    !last 的计算结果为 true,因为这就是 !undefined 的计算结果。

    由于!last 为真,last.length 根本不会被评估。因此,不会引发异常,因为没有实际尝试评估本质上是什么 undefined.length 这是最流行的编程语言的一个特性,称为 布尔短路。一旦 OR 表达式的第一部分计算为真,它右边的任何内容都不会被计算。当左表达式的计算结果为 false 时,相同的原则适用于 AND 语句。

    触发下一行:

    newArr.push([el])
    

    这给了数组一个有效的元素。因此newArr.size 现在是 1。

    在循环的后续迭代中,last 被正确分配为newArr 中的最后一个元素。

    【讨论】:

      【解决方案3】:

      Nina Scholz 建议的一种变体,只是完全摆脱了undefined-magic:

      const chunk = (arr, size) => {
          let last = [];
          let newArr = [last];
          for (let el of arr) {
              if (last.length === size) {
                  last = [];
                  newArr.push(last);
              }
              last.push(el);
          } 
          return newArr
      }
      
      console.log(chunk([1, 2, 3, 4, 5], 2));

      【讨论】:

        猜你喜欢
        • 2018-05-02
        • 2014-10-08
        • 1970-01-01
        • 1970-01-01
        • 2017-02-14
        • 1970-01-01
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多