将Javascript对象的属性从字符串更改为int

将Javascript对象的属性从字符串更改为int

本文介绍了将Javascript对象的属性从字符串更改为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,每个对象都有三个属性(年,总数,人均收入).示例:

I have an array of objects with three properties each (year, total, per_capita).Example:

0: Object
  per_capita: "125.8"
  total: "1007.2"
  year: "2009"

那些属性是字符串,我想创建一个遍历数组并将其转换为int的循环.我尝试了以下循环:

Those properties are strings and I want to create a loop that goes through the array and converts them to int.I tried the following loop:

for (i=0; i<data.length; i++){
    parseInt(data[i].year, 10)
    parseInt(data[i].total, 10)
    parseInt(data[i].per_capita, 10)
}

但是,当我执行typeof(data [0] .total)时,它说是一个字符串.我稍后在程序中遇到问题,我认为这是因为不能正确计算值,因为它们不是正确的类型.任何人都知道问题出在哪里吗?

However when I do typeof(data[0].total) it says its a string.I am having problems later in the program and I think it is because the values cannot be computed properly because they are not the right type.Anyone have an idea where the problem is?

推荐答案

parseInt 不会突变对象,但会解析一个字符串并返回一个整数.您必须将解析后的值重新分配给对象属性.

parseInt does not mutate objects but parses a string and returns a integer. You have to re-assign the parsed values back to the object properties.

for (i=0; i<data.length; i++){
    data[i].year = parseInt(data[i].year, 10)
    data[i].total = parseInt(data[i].total, 10)
    data[i].per_capita = parseInt(data[i].per_capita, 10)
}

这篇关于将Javascript对象的属性从字符串更改为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 14:39