如何将数组传递给函数,然后调用该函数以打印出数组?
我尝试使用下面的代码,但不会在控制台上显示任何内容。
struct Developer {
address owner;
string name;
bytes32 namehash;
bytes32[] skills;
uint256[] skill_levels;
uint wallet;
}
mapping (bytes32=>Developer) public developers_all;
function train(string _name, bytes32 _skill) public {
bytes32 h = keccak256(abi.encodePacked(_name));
require(developers_all[h].owner == msg.sender, "Only the owner of the developer can train them");
require(developers_all[h].wallet >= 150, "Insufficient funds");
uint256 i = 0;
do {
if (developers_all[h].skills[i] == _skill) {
developers_all[h].skill_levels[i]++;
} else if ((i == (developers_all[h].skills.length - 1)) || (developers_all[h].skills.length == 0)) {
developers_all[h].skills.push(_skill);
developers_all[h].skill_levels.push(1);
}
i++;
} while (i < developers_all[h].skills.length);
developers_all[h].wallet = developers_all[h].wallet - 150;
}
答案 0 :(得分:1)
i=list.length-1
不是i=list
。您必须为i
分配数组的长度,而不是整个数组的长度
var array_list = [1,2,3,4,5, "token",6, 7, "best","life", "living"];
function printReverse(list){
for(var i=list.length-1; i >= 0; i--){
console.log(list[i]);
}
}
printReverse(array_list);
答案 1 :(得分:1)
您需要将长度作为索引值提供给i
而不是数组本身。因为当您将数组与>=0
进行比较时,结果为false
,循环结束了。
console.log([1,2,3] >= 0)
var array_list = [1,2,3,4,5, "token",6, 7, "best","life", "living"];
function printReverse(list){
for(var i=list.length-1; i >= 0; i--){
console.log(list[i]);
}
}
printReverse(array_list);
答案 2 :(得分:1)
您需要以list.length - 1
作为初始值。
function printReverse(list) {
for (var i = list.length - 1; i >= 0; i--) {
console.log(list[i]);
}
}
var array_list = [1, 2, 3, 4, 5, "token", 6, 7, "best", "life", "living"];
printReverse(array_list);
一种较短的方法是获取长度并使用while语句对索引进行真实检查。
function printReverse(list) {
var i = list.length;
while (i--) {
console.log(list[i]);
}
}
var array_list = [1, 2, 3, 4, 5, "token", 6, 7, "best", "life", "living"];
printReverse(array_list);