最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I convert every string in split array to a number? - Stack Overflow

programmeradmin0浏览0评论

I have a string that needs to be split and converted into numbers. I decided to split the string and put the strings into an array and later convert them into numbers using the Array.prototype.every() function and the Number() function.

When I check the type of the first array element, I see that I still have a string and not a number. Where is my mistake? The answer here makes it look like after splitting JS would convert to number automatically but that isn't happening as evidenced by logging the type of the first element.

function detectOutlierValue(string) {
    // convert string into array with numbers, 'separator " "
    var numArray = string.split(' ');
    console.log(typeof numArray[0]);
    console.log(numArray);

    numArray.every(function (item) {
        return Number(item);
    });
    console.log(numArray, typeof numArray[0]);

My output is:

string
[ '2', '4', '7', '8', '10' ]
[ '2', '4', '7', '8', '10' ] 'string'

I have a string that needs to be split and converted into numbers. I decided to split the string and put the strings into an array and later convert them into numbers using the Array.prototype.every() function and the Number() function.

When I check the type of the first array element, I see that I still have a string and not a number. Where is my mistake? The answer here makes it look like after splitting JS would convert to number automatically but that isn't happening as evidenced by logging the type of the first element.

function detectOutlierValue(string) {
    // convert string into array with numbers, 'separator " "
    var numArray = string.split(' ');
    console.log(typeof numArray[0]);
    console.log(numArray);

    numArray.every(function (item) {
        return Number(item);
    });
    console.log(numArray, typeof numArray[0]);

My output is:

string
[ '2', '4', '7', '8', '10' ]
[ '2', '4', '7', '8', '10' ] 'string'
Share Improve this question edited May 23, 2017 at 10:29 CommunityBot 11 silver badge asked Mar 3, 2017 at 4:49 heretoinfinityheretoinfinity 1,7443 gold badges21 silver badges39 bronze badges 3
  • That's not how you use every... – Andrew Li Commented Mar 3, 2017 at 4:53
  • Could you specify where the issue is? – heretoinfinity Commented Mar 3, 2017 at 4:55
  • 1. you are doing mistake in splitting. 2. every() is not used like this. 3. you need to use parseInt() to convert string to numbers! – Saurabh Sharma Commented Mar 3, 2017 at 4:57
Add a ment  | 

4 Answers 4

Reset to default 6

You've got your array methods confused. Array.prototype.every is used to determine if every element in an array satisfies a certain condition specified by the callback. Basically, your code is converting every element to a number and then to a boolean for every, and every will return a boolean if the callback returns true for every element it's called on.

Instead, you are looking for Array.prototype.map which performs a function on each element, mapping them to a new value:

var splitString = string.split(' ');
var numArray = splitString.map(Number);

This will map the Number constructor (which is the callback) to every element converting it to a number. Note that numArray holds the transformed array, but splitString still contains the array of strings. Number will return NaN if the string is not numeric.

You're using every incorrectly. every tests to see if every element of an array is true for a certain condition. So the function you have will be applied once for each element present in the array until it finds one where it returns a falsy value. If such an element is found, the every method immediately returns false. What you want is map:

function detectOutlierValue(string) {
  // convert string into array with numbers, 'separator " "
  var numArray = string.split(' ');
  console.log(typeof numArray[0]);
  console.log(numArray);

  numArray = numArray.map(function(item) {
    return Number(item);
  });

  console.log(numArray, typeof numArray[0]);
}

detectOutlierValue("1 2"); 

Here's probably what you wanted to do with every, but it's pointless because it's better to use map

function detectOutlierValue(string) {
  // convert string into array with numbers, 'separator " "
  var numArray = string.split(' ');
  console.log(typeof numArray[0]);
  console.log(numArray);

  var newArr = [];

  numArray.every(function(item) {
    newArr.push(Number(item));
    return true;
  });

  console.log(newArr);
}

detectOutlierValue("1 2");

every is meant to check if each element of an array passes some test. For example:

function isAString(val) {
  return typeof val === 'string'
}
var array =     [ '2', '4', '7', '8', '10' ];
array.every(isAString) //returns true

What you want to do is use the map method

var array = [ '2', '4', '7', '8', '10' ];
var result = array.map(function (x) { 
  return Number(x); 
});

The every() method tests whether all elements in the array pass the test implemented by the provided function.

Source: MDN

So you shouldn't use every() method, instead you can do the following.

var s = "2 3 4 7 8 10";

function detectOutlierValue(string){
// convert string into array with numbers, 'separator " "
	var numArray = string.split(' ');
  
  numArray.every(function (item){
		return Number(item);
	});
  console.log(numArray, typeof numArray[0]);
  
  for(var i=0; i<numArray.length; i++){
  	numArray[i] = Number(numArray[i]);
  }
  console.log(numArray, typeof numArray[0]);
}  

detectOutlierValue(s);

Run the code and notice the difference between the two console outputs.

发布评论

评论列表(0)

  1. 暂无评论