首页 > 解决方案 > 我的 javascript 代码中的错误是什么?我找不到错误

问题描述

此代码使用现有数组将该数据填充到一个空数组中......

然后它会创建一个循环来检查它们是否小于 18 或大于等于 18。

var years = [1990, 2001, 1975, 2004, 1998, 1993];
var empty = [];
for (i = 0; i <= years.length - 1; i++) {
  empty.push(years[i]);
}
console.log(empty);
for (a = 0; a <= empty.length - 1; a++) {
  if (2018 - empty[a] < 18) {
    console.log(empty[a] + ' is not eighteen or older: ' + 2018 - empty[a]);
  } else {
    console.log(empty[a] + ' is eighteen or older: ' + 2018 - empty[a]);
  }
}

标签: javascript

解决方案


它与字符串连接有关。因为2018是一个数字,它希望在这些控制台日志中进行数字加法。我改用模板文字修改了您的代码,它工作正常。如果您不想使用模板文字,只需在计算末尾添加括号2018 - empty[a]即可(2018 - empty[a])

var years = [1990, 2001, 1975, 2004, 1998, 1993];
var empty = [];
for (let i = 0; i < years.length; i += 1) {
  empty.push(years[i]);
}
console.log(empty);
// using template literals
for (let a = 0; a < empty.length; a += 1) {
  if (2018 - +empty[a] < 18) {
    console.log(`${empty[a]} is not eighteen or older: ${2018 - empty[a]}`);
  } else {
    console.log(`${empty[a]} is eighteen or older: ${2018 - empty[a]}`);
  }
}

// regular string concatenation
for (let a = 0; a < empty.length; a += 1) {
  if (2018 - +empty[a] < 18) {
    console.log(empty[a] + ' is not eighteen or older:' + (2018 - empty[a]));
  } else {
    console.log(empty[a] + ' is eighteen or older:' + (2018 - empty[a]));
  }
}


推荐阅读