简体   繁体   English

Javascript检查字符串中的每个字符,并在相应位置返回数组元素

[英]Javascript check every char in a string and return array element on corresponding position

Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array. 得到了一个由一系列0或1位和一个值数组组成的字符串,如果字符串中的字符被设置为1,则需要从数组中返回相应的值。 example: mystring = "0101"; 例如:mystring =“ 0101”; myarray =["A","B","C","D"]; myarray = [“ A”,“ B”,“ C”,“ D”]; then result = "B,D" how can I get this result? 然后结果=“ B,D”我怎么得到这个结果?

  for(var i=0;i<mystring.length;i++){
    if(mystring[i] != 0)
 {
 result = myarray[i];
 }
  }

Your code seems to work just fine, so you can just add another array and push the values on to that: 您的代码似乎可以正常工作,因此您可以添加另一个数组并将值压入该数组:

var result = [];
for (var i = 0 ...
    result.push(myarray[i]);

http://jsfiddle.net/ExplosionPIlls/syA2c/ http://jsfiddle.net/ExplosionPIlls/syA2c/


A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index. 一种更聪明的方法是将过滤器应用于myarray ,以检查相应的mystring索引。

myarray.filter(function (_, idx) {
    return +mystring[idx];
})

http://jsfiddle.net/ExplosionPIlls/syA2c/1/ http://jsfiddle.net/ExplosionPIlls/syA2c/1/

Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. 遍历二进制字符串中的字符(如果遇到1),将数组对应索引处的值添加到临时数组中。 Join the temporary array by commas to get the output string. 用逗号连接临时数组以获取输出字符串。

I am not really sure if this is what you are looking for, but this returns the array of matches. 我不太确定这是否是您要查找的内容,但这将返回匹配项数组。

   var result = [];
   for(var i=0;i<mystring.length;i++){
       if(parseInt(mystring[i]) !== 0 ) {
          result.push(myarray[i]);
       }
   }
   return result;

result = new Array(); 结果= new Array(); for(var i=0;i 对于(var i = 0; i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM