使用循环和条件语句比较数组中的元素
comparing elements in an array using loops and conditional statements
这是我被要求做的事情:
给定一个项目数组,检查每对项目是否相等和等价,并记录结果
例如,
var arItems = [2,2,"2",true,'6'];
将输出以下内容:
2和2是等价的
2和2相等但不等价
2 和 true 既不相等也不等价
true 和 false 既不相等也不等价
您不能使用 === 运算符,因此您必须使用 if/else 并循环检查每一对
您的数组应至少包含 5 项,展示每个有效输出
您的代码必须易于修改才能更改数组中的项目
这是我目前拥有的:
var arItems = [2, 2, "2", true, '6'];
for ( x = 0; x < 5; x++)
{
for ( y = 1; y < 5; y++)
{
if (typeof arItems [x]== typeof arItems [y] && arItems [x] == arItems [y])
{
console.log (arItems [x] + " and " + arItems [y] + " are equivalent");
}
else if (arItems [x] == arItems [y] && typeof arItems [x] != arItems [y])
{
console.log (arItems [x] + " and " + arItems [y] + " are equal but not equivalent");
}
else
{
console.log ( arItems [x] + " and " + arItems [y] + " are neither equal nor equivalent");
}
}
}
我试图让它检查以下对:
2 & 2 。
2 & 2 。
2 & "2" 。
“2” & 真。
真 & '6'
我不确定我是否可以在代码中添加一些东西以允许它自动 运行 ,或者我是否必须写出整个代码以使其完全按照它们的原样进行。这就是说它正在比较索引
例子:
索引 [0,1,2,3,4]
被比较的对:
0 & 1 。
1 和 2。
2 和 3。
3 & 4
您可以使用从索引 1
开始并结束的单个 for
循环以这种方式迭代项目。您可以通过从当前索引中减去 1 来引用每对的前一个元素。
我还更新了您的条件代码,只是为了展示它在实践中更有可能完成的方式。
var items = [2, 2, "2", true, '6'];
for (var i = 1; i < items.length; i++) {
var item1 = items[i - 1];
var item2 = items[i];
if (item1 === item2) {
console.log(item1, "and", item2, "are equivalent");
} else if (item1 == item2) {
console.log(item1, "and", item2, "are equal but not equivalent");
} else {
console.log(item1, "and", item2, "are neither equal nor equivalent");
}
}
这是我被要求做的事情: 给定一个项目数组,检查每对项目是否相等和等价,并记录结果 例如,
var arItems = [2,2,"2",true,'6'];
将输出以下内容: 2和2是等价的 2和2相等但不等价 2 和 true 既不相等也不等价 true 和 false 既不相等也不等价
您不能使用 === 运算符,因此您必须使用 if/else 并循环检查每一对
您的数组应至少包含 5 项,展示每个有效输出
您的代码必须易于修改才能更改数组中的项目
这是我目前拥有的:
var arItems = [2, 2, "2", true, '6'];
for ( x = 0; x < 5; x++)
{
for ( y = 1; y < 5; y++)
{
if (typeof arItems [x]== typeof arItems [y] && arItems [x] == arItems [y])
{
console.log (arItems [x] + " and " + arItems [y] + " are equivalent");
}
else if (arItems [x] == arItems [y] && typeof arItems [x] != arItems [y])
{
console.log (arItems [x] + " and " + arItems [y] + " are equal but not equivalent");
}
else
{
console.log ( arItems [x] + " and " + arItems [y] + " are neither equal nor equivalent");
}
}
}
我试图让它检查以下对: 2 & 2 。 2 & 2 。 2 & "2" 。 “2” & 真。 真 & '6' 我不确定我是否可以在代码中添加一些东西以允许它自动 运行 ,或者我是否必须写出整个代码以使其完全按照它们的原样进行。这就是说它正在比较索引 例子: 索引 [0,1,2,3,4] 被比较的对: 0 & 1 。 1 和 2。 2 和 3。 3 & 4
您可以使用从索引 1
开始并结束的单个 for
循环以这种方式迭代项目。您可以通过从当前索引中减去 1 来引用每对的前一个元素。
我还更新了您的条件代码,只是为了展示它在实践中更有可能完成的方式。
var items = [2, 2, "2", true, '6'];
for (var i = 1; i < items.length; i++) {
var item1 = items[i - 1];
var item2 = items[i];
if (item1 === item2) {
console.log(item1, "and", item2, "are equivalent");
} else if (item1 == item2) {
console.log(item1, "and", item2, "are equal but not equivalent");
} else {
console.log(item1, "and", item2, "are neither equal nor equivalent");
}
}