[英]Working with Knockout 'foreach' looping through multidimensional array
[英]Looping through array with forEach
我正在尝试制作一个循环遍历数组并将“位置”和“距离”记录到控制台的基本程序。 我的程序没有按预期运行,不会将值记录到控制台。 我做错了什么,我该如何解决?
let destinations = [
{place: ['Dubai'],
distance: 7276},
{place: ['Sydney'],
distance: 8759},
{place: ['London'],
distance: 4166},
{place: ['tokyo'],
distance: 5754},
{place: ['Seoul'],
distance: 6037},
];
destinations.forEach(spot => {
if (spot.length < 6) {
console.log(`${spot} is an interesting vacation spot.
Let's see how far it is before we pull the trigger`);
destinations.forEach(howFar => {
if (howFar < 6000) {
console.log(`${spot} is close enough. Let's go there!`);
} if (howFar > 6000) {
console.log(`Nevermind. ${spot} is too far.`);
}});
}
});
您需要非常仔细地逐步执行代码,以尝试查看 JS 解释器看到的内容。 在草稿纸上记下变量的值以及它们在循环时如何变化会有所帮助。 这将帮助您看到自己的错误:
destinations.forEach(spot => {
什么是spot
? 它将是destinations
的每个值,因此例如在第一次迭代中它将是{place: ['Dubai'],distance: 7276}
。
if (spot.length < 6) {
{place: ['Dubai'],distance: 7276}
的length
属性是多少? 这看起来不像它有length
属性。 它不是一个数组。 另外,你在这里检查什么条件? 你确定你需要一个 if 语句吗?
console.log(`${spot} is an interesting vacation spot.
Let's see how far it is before we pull the trigger`);
您希望看到什么在这里将spot
放在字符串中? 它的值为{place: ['Dubai'],distance: 7276}
。 您确定不想从 object 中获取一些值以放入字符串中吗?
destinations.forEach(howFar => {
这不是在你之前循环过的同一个数组上循环吗? 给定 6 个目的地,这意味着它将运行 36 次。 howFar
是什么? 因为它来自destinations.forEach
,所以它将是destinations
数组中的对象之一。
if (howFar < 6000) {
destinations
数组中的 object 是否与数字相当? 它是一个 object,所以这是行不通的。 您是要访问 object 的distance
属性吗?
我的第一条建议是简化您的destinations
数组。 place
目前是一个字符串数组,但它们都是单个项目,因此您可能不需要一个数组。 此外,由于您没有更改destinations
,您可以将它设为一个const
变量,这很有用,因为它可以让查看您的代码的人知道他们不必担心找到可能发生变化的地方:
const destinations = [
{place: 'Dubai', distance: 7276},
{place: 'Sydney', distance: 8759},
{place: 'London', distance: 4166},
{place: 'Tokyo', distance: 5754},
{place: 'Seoul', distance: 6037},
];
您循环遍历目的地的方式很好,但是您需要访问 object 的属性,并且您不需要无关的内部循环和 if 语句(除非您打算用它做一些我不想做的事情理解)。
destinations.forEach(spot => {
console.log(`${spot.place} is an interesting vacation spot.
Let's see how far it is before we pull the trigger`);
if (spot.distance < 6000) {
console.log(`${spot.place} is close enough. Let's go there!`);
} else {
console.log(`Nevermind. ${spot.place} is too far.`);
}
});
你基本上是在做一个 Object.length,它不存在。 试试 spot.place 或 spot.distance 之类的东西。
此外,您不能在目的地内执行 destinations.forEach。 这真的有必要吗? 尝试这样的事情:
destinations.forEach(spot => {
if (spot.place.length < 6) {
console.log(`${spot.place} is an interesting vacation spot.
Let's see how far it is before we pull the trigger`);
if (spot.distance < 6000) {
console.log(`${spot.place} is close enough. Let's go there!`);
} else {
console.log(`Nevermind. ${spot.place} is too far.`);
}
}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.