【问题标题】:Why does shift() work on one array but not the other, unless applied generically on the other为什么 shift() 对一个数组起作用而不对另一个起作用,除非一般应用于另一个
【发布时间】:2017-07-15 23:13:01
【问题描述】:

在下面的代码中,编译器(在“编译”时)没有抱怨groups.shift(),但抱怨depths.shift() 不是函数。我对什么视而不见? (我尝试重命名depths,重新输入等)

    const tag1x = (elem, content, groups = ['?','?','?'], depths = ['?','?'], optional = true, level = 0) => {
        let option = optional ? '?' : '';
        let template = `
            ${'\t'.repeat(level)}(${groups.shift()}:<$1[^>]*?DDD(${depths.shift()}:[0-9]+)[^>]*>)$3
            ${'\t'.repeat(level)}(${groups.shift()}:$2)
            ${'\t'.repeat(level)}(${groups.shift()}:</$1[^>]*?DDD(${depths.shift()}:[0-9]+)[^>]*>)$3
            `;
        return form(template, elem, content, option);
    }

但是,如果我一般使用shift,它在所有方面都可以正常工作:

    const tag1x = (elem, content, groups = ['?','?','?'], depths = ['?','?'], optional = true, level = 0) => {
        let option = optional ? '?' : '';
        let template = `
            ${'\t'.repeat(level)}(${groups.shift()}:<$1[^>]*?DDD(${[].shift.call(depths)}:[0-9]+)[^>]*>)$3
            ${'\t'.repeat(level)}(${groups.shift()}:$2)
            ${'\t'.repeat(level)}(${groups.shift()}:</$1[^>]*?DDD(${[].shift.call(depths)}:[0-9]+)[^>]*>)$3
            `;
        return form(template, elem, content, option);
    }

以上功能齐全。

【问题讨论】:

    标签: javascript arrays templates shift


    【解决方案1】:

    我看错了情况。该错误发生在运行时,因此很明显是因为字符串输入而不是数组输入。字符串输入将由[].shift.call(myAccidentallyAString) 修复,当然,直接在字符串上调用shift() 不是函数。

    它的作用类似于Array.isArray(myStuff) ? myStuff.shift() : [myStuff].shift(),这是有道理的,因为(我猜)myStuff 被装箱到一个对象,然后被shift() 调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      相关资源
      最近更新 更多