简体   繁体   English

如何使用forEach将数组中的字符串转换为数字?

[英]How do I convert strings in an array to numbers using forEach?

I am trying to sum the contents of an array like these: 我试图总结像这样的数组的内容:

var cardsBen = [10,2] var cardsBen = [10,2]

var cardsAmy = [4,10] var cardsAmy = [4,10]

When I use a for loop, it works. 当我使用for循环时,它可以工作。

for(var i = 0; i < cardsBen.length; i++){
  cardsBen[i] = Number(cardsBen[i]);
}

When I use forEach, it doesn't convert. 当我使用forEach时,它不会转换。

cardsAmy.forEach(function(item)
  {
    Number(item);
  });

I know this because, when I then reduce the arrays, I get 12 for Ben and 410 for Amy. 我知道这是因为,当我减少阵列时,我得到12个Ben和410个Amy。

var sumBen = cardsBen.reduce(function(sum, nbr){return sum + nbr});
var sumAmy = cardsAmy.reduce(function(sum, nbr){return sum + nbr});

Primitive values can't be mutated. 原始值不能被突变。 So when doing Number(item) you have to assign that back to the array like: 因此,在执行Number(item)您必须将其分配回数组,例如:

cardsAmy.forEach(function(item, i) {
    cardsAmy[i] = Number(item);
});

And you can do that directly in reduce (without needing the above forEach code) like: 您可以直接在reduce执行此操作(不需要上面的forEach代码),例如:

var sumBen = cardsBen.reduce(function(sum, nbr) { return sum + Number(nbr); }, 0);
//                                                             ^^^^^^^   ^

You could use reduce with an implicit casting to number with an unary plus + . 您可以使用带有隐式强制转换的reduce到带有一元加号+

sum = array.reduce(function (s, v) {
    return s + +v;
}, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字符串数组转换为数字...是map()的唯一方法? - How do you convert an array of strings into numbers… is the only way map()? 使用map转换字符串数组中的数字数组 - convert array of numbers in array of strings using map 如何使用 forEach 将字符串数组转换为单个字符串 - How do I use forEach to turn an array of strings into a single string 如何将字符串数组转换为数字数组? - how to convert an array of strings to array of numbers? 如何将对象数组转换为元素数组,然后使用 map 和 foreach 方法将它们放在主 div 根元素中? - How do I convert an array of objects to an array of elements, and then place them inside main div root element by using map and foreach methods? 如何在javascript中将字符串数组转换为对象属性? - How do I convert an array of strings to an object property in javascript? 如何将特定字符串转换为数组中的特定数字? - How do I convert specific strings into specific number in an array? 如何将数组中的所有数字转换为对应的月份? - How do i convert all numbers in an array to their corresponding month? 将字符串数组转换为数字数组 - convert array of numbers that are strings into array of numbers javascript-将字符串和数字数组转换为数字数组 - javascript - convert an array of strings and numbers to an array of numbers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM