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

javascript - What is the opposite of indexOf? - Stack Overflow

programmeradmin3浏览0评论

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 try yourArray[x], where x is the position you are looking for – Marco Commented Sep 24, 2013 at 6:01
Add a ment  | 

4 Answers 4

Reset to default 5
function 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

发布评论

评论列表(0)

  1. 暂无评论