Javascript NaN bug

时间:2016-03-12 15:13:06

标签: javascript html nan

这是我的js功能。当我输入数据时,我得到NaN

//BMI is defined as BMI = ( Weight in Pounds / ( Height in inches x Height in inches ) ) x 703
function calculatebmi(weight, height){
    //window.alert("hello");
    var weight = parseInt(document.getElementsByName("weight_pounds"));
    var height = parseInt(document.getElementsByName("height_inches"));

    var bmi = parseInt(((weight/height)*703));
    window.alert("your BMI is: " + bmi);
}

我尝试过math.floor和innerHTML。两者都没有帮助。

输入标签类型是数字,以防有人想知道。

3 个答案:

答案 0 :(得分:4)

document.getElementsByName返回{ "name": "a2app", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "self", "license": "ISC", "dependencies": { "angular2": "2.0.0-beta.9", /developement/lib/ - how to add this? "systemjs": "0.19.24", "es6-promise": "^3.0.2", "es6-shim": "^0.33.3", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.2", "zone.js": "0.5.15" }, "devDependencies": { "browser-sync": "^2.11.1", "gulp": "^3.9.1", "gulp-stylus": "^2.3.1", "gulp-typescript": "^2.12.1" } }

您需要使用NodeList表示法从此集合中获取第一个元素,然后使用[0]属性。

value

对于var value = document.getElementsByName('weight_pounds')[0].value; var weight = parseInt(value, 10); 函数parseInt(第二个参数)默认为radix,但您需要指定它。 来自MDN:

  

始终指定此参数以消除读者混淆并保证可预测的行为。

答案 1 :(得分:2)

尝试传递parseInt内的值而不是节点对象

 var weight = parseInt(document.getElementsByName("weight_pounds")[0].value);

如果将对象传递给parseInt而不是数字字符串,它将返回NaN。另外,建议使用radix的{​​{1}}参数作为parseInt,但现在最近的浏览器默认会将基数视为10。

请注意,10将返回html集合,因此您无法直接访问required元素的值。您必须使用括号表示法getElementsByName获取其第一个元素并访问其值。因此,为了避免此类问题,您可以使用[0],如下所示,

.querySelector()

答案 2 :(得分:0)

当您尝试解析其值时(from concurrent.futures import ThreadPoolExecutor, wait apple = { 'a': b"first pdf", 'b': b"second pdf" } def write_to_file(file_pair): name, data = file_pair filename = "output/%s.pdf" % (name) with open(filename, "wb") as f: f.write(data) # Set max_workers to the number of threads you wish to use (4 is good) with ThreadPoolExecutor(max_workers=4) as executor: res = executor.map(write_to_file, apple.items()) ),您尝试解析节点本身,并且您不会将.value返回的集合编入索引:

getElementsByName