javascript - 我的 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]);
}
}
解决方案
它与字符串连接有关。因为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]));
}
}
推荐阅读
- c# - 为什么控制器返回 view() 中的操作可以指向其他同名视图?
- elasticsearch - ElasticSearch:嵌套桶聚合
- python - 将图像输入已经训练好的 TensorFlow CNN
- javascript - VueJS - 将数据从父组件传递到子组件
- matlab - Matlab parfor 未分类变量
- python - 如何将一个对象批量关联到具有 ManyToManyField 的多个对象?
- php - 如何实际使用 PHP Transliterator (Romanization) 将波斯语转换为英式英语
- ios - 如何让 LazyVGrid 不偷懒?
- javascript - 如何在网页中插入三角形状?
- mysql - MYSQL 平均最大值