简体   繁体   中英

Find the nth character from an array of words in JavaScript

I'd like to create a function (nthChar) that takes 1 parameter - an array of n words.

The function should concatenate the nth letter from each word to construct a new word which should be returned as a string.

The nth letter should be the 1st from the first word in the array, the second from the second word in the array, the third from the third and so on. So: nthChar(['I','am','Tom']) should return 'Imm'

Here's my attempt: function nthChar(words){

for (var i=0; i<words.length; i++) {
return words[i].charAt(words.indexOf(words[i]))
}
}

Which only seems to grab the first letter of the first word. How would I proceed to the other words of the array before concatenation?

With minimal changes to your code, you can do this

function nthChar(arr) {
    var str = '';
    for (var i=0; i<words.length; i++) {
        str = str + words[i][i];
    }
    return str;
}

str - used to build up the result string

words[i] selects the i'th word ... the second [i] in that statement selects the i'th letter in that word

for example: "Hello World"[6] is W

Bonus: works in IE8 and earlier ...


and, just for the hell of it, void 's answer in ES6

var nthChar = arr => arr.map((i, v) => i[v]).join('');
function nthChar(arr){

  return arr.map(function(i, v){
      return i[v];
  }).join("");

}

console.log(nthChar(['I','am','Tom']));

So it is returning an array of the characters you want and then it is joining it. Makes sense?

The issue with your code was that you were not concatenating anything to the output. You can access the characters of a string as if it is an array .

Live Fiddle

Your code can be:

function nthChar(words){
    var str = "";
    for (var i=0; i<words.length; i++) {
       str += words[i].charAt(i);
    }
    return str;
}

Fiddle

Try something like this

function nthChar(words){
  var result = "";
  for (var i = 0, ln = words.length; i<ln; i++) 
    result += words[i].charAt(i);
  return result;
}

This can be as simple as

function nthChar(words){
    var s = "";
    for(var i=0;i<words.length;i++){
      s+= words[i].charAt(i);
    }
    return s;
}

Live example: http://jsfiddle.net/11yc79jn/

This is closest to your original solution, and just uses the loop control variable i which is incrementing already as you loop through the words array. Of course, also return after the entire loop has run as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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