What would be the opposite of .indexOf()? I used a regexp to find numbers in a string and now I want to add them together:
function getnum(str){
var nums= str.match(/\d+/g);
return //30+83//
}
getnum("sdsoi30adsd83")
Is there some sort of .charAt() equivalent for arrays I could use for this?
I'm sorry this is a very beginner question. I've been up all day coding and I realize the answer may be very obvious but I've looked all over devdocs.io to no luck.
What would be the opposite of .indexOf()? I used a regexp to find numbers in a string and now I want to add them together:
function getnum(str){
var nums= str.match(/\d+/g);
return //30+83//
}
getnum("sdsoi30adsd83")
Is there some sort of .charAt() equivalent for arrays I could use for this?
I'm sorry this is a very beginner question. I've been up all day coding and I realize the answer may be very obvious but I've looked all over devdocs.io to no luck.
Share Improve this question asked Sep 24, 2013 at 5:59 user2755667user2755667 1-
1
If you want to hop into a certain field in an
array
, why don't you tryyourArray[x]
, wherex
is the position you are looking for – Marco Commented Sep 24, 2013 at 6:01
4 Answers
Reset to default 5function getnum(str){
var nums= str.match(/\d+/g);
var total=0;
for(var i=0;i<nums.length;i++)
{
total+=Number(nums[i]);
}
return total;
}
getnum("sdsoi30adsd83");
For example char at 5th character is
"sdsoi30adsd83"[4]
which is "i"
return nums.reduce(function(c, n) {
return c + parseInt(n);
}, 0);
Demo here - http://jsfiddle/TyV3s/
You could also use ES5 map-reduce function for this problem.
Of course the for-loop solution works fine.
function getnum(str){
var nums= str.match(/\d+/g);
console.log(nums);
return nums.map(function (str) {
// convert to a Int array
return parseInt(str);
}).reduce(function (prev, curr) {
return prev+curr;
}, 0);
}
console.log('result=' + getnum("sdsoi30adsd83"));
As to your original question, the opposite of indexOf()
is indexing by .
or []
.
var a = "sdsoi30adsd83";
a[a.indexOf('3')]; // = "3"
https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods