Javascript使用函数Number()在map()函数内将字符串转换为数字

时间:2018-06-09 05:44:39

标签: javascript function dictionary reduce

我想转换对象数组中给出的imdb等级。我正在尝试使用地图功能,但它没有发生。 newList只提供旧列表,不做任何更改。我做错了什么?

var watchList = [
                {  

                   "Metascore": "74",
                   "imdbRating": "8.8",
                   "imdbVotes": "1,446,708",
                   "imdbID": "tt1375666",
                   "Type": "movie",
                   "Response": "True"
                },
                {  
                   "Metascore": "74",
                   "imdbRating": "8.6",
                   "imdbVotes": "910,366",
                   "imdbID": "tt0816692",
                   "Type": "movie",
                   "Response": "True"
                },
                {
                   "Metascore": "82",
                   "imdbRating": "9.0",
                   "imdbVotes": "1,652,832",
                   "imdbID": "tt0468569",
                   "Type": "movie",
                   "Response": "True"
                }
];



let newList=[];
newList=watchList.map(function(list){
  Number(list.imdbRating);
  return list;
});
console.log(newList);

2 个答案:

答案 0 :(得分:1)

声明Number不会改变原始值。如果您希望对象的属性的imdbRating为数字,则必须指定

var watchList=[{"Metascore":"74","imdbRating":"8.8","imdbVotes":"1,446,708","imdbID":"tt1375666","Type":"movie","Response":"True"},{"Metascore":"74","imdbRating":"8.6","imdbVotes":"910,366","imdbID":"tt0816692","Type":"movie","Response":"True"},{"Metascore":"82","imdbRating":"9.0","imdbVotes":"1,652,832","imdbID":"tt0468569","Type":"movie","Response":"True"}];

watchList.forEach(function(list){
  list.imdbRating = Number(list.imdbRating);
});
console.log(watchList);

请注意,对象在Javascript中通过引用传递 - 更改对象的引用中的某些内容将更改原始对象,这就是我使用forEach而不是.map的原因。如果要创建全新的对象(而不是改变原始对象),请使用对象扩展以及map

var watchList=[{"Metascore":"74","imdbRating":"8.8","imdbVotes":"1,446,708","imdbID":"tt1375666","Type":"movie","Response":"True"},{"Metascore":"74","imdbRating":"8.6","imdbVotes":"910,366","imdbID":"tt0816692","Type":"movie","Response":"True"},{"Metascore":"82","imdbRating":"9.0","imdbVotes":"1,652,832","imdbID":"tt0468569","Type":"movie","Response":"True"}];

const newList = watchList.map(({ imdbRating, ...rest }) => ({
  imdbRating: Number(imdbRating),
  ...rest,
}));
console.log(newList);

答案 1 :(得分:0)

如果您想要从字符串快速转换为整数,可以使用+运算符。

示例:

var newList=[];
newList=watchList.map(function(list){
    list.imdbRating = +list.imdbRating;  
    return list;
});