gpt4 book ai didi

javascript - JS 中的数组有问题

转载 作者:行者123 更新时间:2023-11-28 19:17:10 27 4
gpt4 key购买 nike

这就是我想做的事情

// declare an array with 16 items, each with intial value = 0
var countMe = [
["00", 0],
["01", 0],
["02", 0],
["03", 0],
["10", 0],
["11", 0],
["12", 0],
["13", 0],
["20", 0],
["21", 0],
["22", 0],
["23", 0],
["30", 0],
["31", 0],
["32", 0],
["33", 0]
];

// calculate number of items for each array item by adding +1 to its previous value
$.each(dataFruits, function (index, item) {
if (item.weight > -1 && item.quantity > -1) {
countMe["" + item.weight + item.quantity, 1][1] = countMe["" + item.weight + item.quantity, 1][1] + 1;
}
});

// go through array and call method for each array item whose value is more then zero
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
if (countMe["" + i + j, 1][1] > 0) {
CreateText(countMe["" + i + j, 1][1], "black", 33, countMe["" + i + j, 0][0]);
}
}
}

问题

  1. 我无法获取数组的值

  2. 我能够更新其值

它不会抛出任何错误,只是没有给我任何值(value)。

最佳答案

在这种情况下,您应该使用普通的 JavaScript 对象(键值对)。

// Create a JavaScript object
var countMe = {};

for (var i = 0; i < 4; i += 1) {
for (var j = 0; j < 4; j += 1) {
// Create new keys and initialize them with 0.
countMe["" + i + j] = 0;
}
}

console.log(countMe);

将是

{ '10': 0,
'11': 0,
'12': 0,
'13': 0,
'20': 0,
'21': 0,
'22': 0,
'23': 0,
'30': 0,
'31': 0,
'32': 0,
'33': 0,
'00': 0,
'01': 0,
'02': 0,
'03': 0 }

这样我们就创建了一个 JavaScript 对象,然后你就可以像这样计数了

$.each(dataFruits, function (index, item) {
if (item.weight > -1 && item.quantity > -1) {
countMe["" + item.weight + item.quantity]++;
}
});

这里,countMe[""+ item.weight + item.quantity]++ 将增加 ""+ item.weight + item.quantity 对应的数字。例如,如果 weight1 并且 quantity2 则该值变为 countMe["12"] 并且其对应的值将会增加。

现在您已经计算了值,您可以调用该函数,如下所示

for (var i = 0; i < 4; i += 1) {
for (var j = 0; j < 4; j += 1) {
if (countMe["" + i + j] > 0) {
CreateText(countMe["" + i + j], "black", 33, "" + i + j);
}
}
}

实际问题

当你这样做时

countMe["" + item.weight + item.quantity, 1]

索引部分

"" + item.weight + item.quantity, 1

将始终被计算为 1,因为逗号运算符将其中的最后一个元素作为表达式的结果。您可以这样确认

console.log((1, 2, 3, 4));
// 4

var a = (1, 2, 3, 4);
console.log(a);
// 4

因此,您始终访问 ["01", 0],因为它是索引 1 处的元素,然后您始终仅递增该值。

关于javascript - JS 中的数组有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29599353/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com