抓住一个数组的元素

时间:2017-04-23 09:05:38

标签: javascript if-statement foreach

var input = prompt();
var binput = input.split("");
var inputl = input.split(" ").length

if ( inputl % 5 == 0 ) {
    binput.forEach(function(v, i) {
        if (v === "a") {
            binput[i] = "$"
        }
    })
}

我的问题是,我只想更改inputl的第5个第10个第15个...元素,现在它会更改整个文本if (inputl % 5 == 0)。但是我只想抓住inputl数组的第五个元素。

2 个答案:

答案 0 :(得分:1)

  

我的问题是我只想要5月10日15日

试试这个

binput.forEach(function(v, i) { //iterate once
     if( (i + 1 ) % 5 == 0)  //check if the element is 5th, 10th, 15th etc
     {
         binput[i] = "$"; //assign the value as you like
     }
}};

修改

如果您还想在为其指定新值之前检查该值是否为“a”,请尝试

binput.forEach(function(v, i) { //iterate once
     if( v == "a" && ( (i + 1 ) % 5 == 0 ) )  //check if the element is 5th, 10th, 15th etc
     {
         binput[i] = "$"; //assign the value as you like
     }
}};

答案 1 :(得分:0)

if ( inputl % 5 == 0 ){    
  binput.forEach(function(v, i) {  
     if( (i + 1 ) % 5 == 0) {    
        if(v === "a") {    
  binput[i] = "$"    
}}    
})}    

我得到了它,谢谢你的时间