对不起,对不起。我正在尝试编写代码,此时将电话号码列表作为字符串,找到其数字的总和并将其放入新数组中。我对此感觉很好,但是当我运行它时,我得到一个只包含后一个数的数组,而不是索引中的第一个。
var numList = ["555-237-4892", "555-236-44892", "233-482-1049"];
var penList = [];
for (var j = 0; j < numList.length; j++) {
function sum() {
var phonestr = numList[j];
var phoneArray = phonestr.split("");
delete phoneArray[3];
delete phoneArray[7];
phoneArray.sort();
phoneArray.pop();
phoneArray.pop();
var total = 0;
var phoneInt;
var largest = 0;
for (var i = 0; i < phoneArray.length; i++) {
phoneInt = parseInt(phoneArray[i]);
total += phoneInt;
}
penList[i] = total;
};
sum();
};
console.log(penList);
答案 0 :(得分:0)
如果我理解你要做的事情,我想你想改变这个:
penList[i] = total;
到此:
penList[j] = total;
而且,这是一种更为浓缩的方式:
var numList = ["555-237-4892", "555-236-44892", "233-482-1049"];
var result = numList.map(function(item) {
return item.replace(/\D/g, "").split("").reduce(function(total, ch) {
return total + parseInt(ch, 10);
}, 0);
});
// display result in snippet
document.write(JSON.stringify(result));
&#13;
说明:
numList
上调用地图,以便迭代数组.replace()
.split()
答案 1 :(得分:0)
将外部for循环中的penList[i]
更改为penList[j]
。
此外,如果您不需要,如果您要立即调用它,则不需要在for循环中声明sum()
函数。如果您正在进行模块化代码,那么最好将该功能移出循环以获得更好的可读性。
答案 2 :(得分:0)
试试这个:
按照说明进行解释
var numList = ["555-237-4892","555-236-44892","233-482-1049"];
var penList = [];
for (var j = 0; j < numList.length; j++) {
function sum() {
var phonestr = numList[j];
var phoneArray = phonestr.split("");
//remove the first "-" from array
// now you have 1 char less in array
phoneArray.splice(3, 1);
//remove the second "-" from array
//the second '-' is not at index 7 since we already removed 1index in previous step its at index 6
phoneArray.splice(6, 1);
phoneArray.sort();
phoneArray.pop();
phoneArray.pop();
var total = 0;
var phoneInt;
var largest = 0;
for (var i = 0; i < phoneArray.length; i++) {
phoneInt = parseInt(phoneArray[i]);
total += phoneInt;
}
//this should be j not i since we are in ouer loop
penList[j] = total;
};
sum();
};