【问题标题】:My value1.length is receiving a length undefined error. The value2.length and value3.length aren't receiving errors我的 value1.length 收到长度未定义的错误。 value2.length 和 value3.length 没有收到错误
【发布时间】:2022-01-12 04:57:39
【问题描述】:

Value1.length 正在发送一个未定义的错误,但其他两个值不是。为什么只有第一个值没有正常运行?

placeOrder.addEventListener("click", function (e) {
    e.preventDefault();

    var value1 = input1.value;
    if (value1.length < 1) {
        value1 = 0;
        coffeeTotal = 0;
    } else {
        coffeeTotal = coffeePrice * parseInt(value1);
    }

    var value2 = input2.value;
    if (value2.length < 1) {
        value2 = 0;
        bagelTotal = 0;
    } else {
        bagelTotal = bagelPrice * parseInt(value2);
    }

    var value3 = input3.value;
    if (value3.length < 1) {
        value3 = 0;
        biscottiTotal = 0;
    } else {
        biscottiTotal = biscottiPrice * parseInt(value3);
    }

    var total = coffeeTotal + bagelTotal + biscottiTotal;
    console.log(total);


});

【问题讨论】:

  • 什么是input1, input2, input3
  • input1 的值在哪里分配,它应该是什么?在coffeePrice * parseInt(value1) 中使用 parseInt 是多余的,因为乘法无论如何都会强制参数类型为 number。
  • var input1 = document.getElementById("coffee"); var input2 = document.getElementById("bagel"); var input3 = document.getElementById("biscotti");
  • 请先添加console.log(document.getElementById("coffee"));,看看能不能找到那个DOM元素

标签: javascript dom


【解决方案1】:

typeerror: cannot read property “values” from undefined 的真正含义是什么?

要理解这一点,您首先需要了解 JavaScript 中未定义的含义。让我们看一个使用变量的简单示例:

// This line is a variable declaration
// we create it, but do not assign it a value 
// so it is undefined
var a; 
// In this line we declare and assign a variable
// this is not undefined 
var b = 6;

当它是一个期望持有一个值的引用但实际上什么都没有引用的对象时,某些东西是未定义的。 所以你必须检查你的 input1 的值。

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    相关资源
    最近更新 更多